I need to know the current time at CDT when my Python script is run. However this script will be run in multiple different timezones so a simple offset won't work. I only need a solution for Linux, but a cross platform solution would be ideal.
You can use time.gmtime()
to get time GMT (UTC) from any machine no matter the timezone, then you can apply your offset.
pytz or dateutil.tz is the trick here. Basically it's something like this:
>>> from pytz import timezone
>>> mytz = timezone('Europe/Paris')
>>> yourtz = timezone('US/Eastern')
>>> from datetime import datetime
>>> now = datetime.now(mytz)
>>> alsonow = now.astimezone(yourtz)
The difficulty actually lies in figuring out which timezone you are in. dateutil.tz is better at that.
>>> from dateutil.tz import tzlocal, gettz
>>> mytz = tzlocal()
>>> yourtz = gettz('US/Eastern')
If you want all the nitty gritty details of why timezones are evil, they are here:
http://regebro.wordpress.com/2007/12/18/python-and-time-zones-fighting-the-beast/
http://regebro.wordpress.com/2008/05/10/python-and-time-zones-part-2-the-beast-returns/
http://regebro.wordpress.com/2008/05/13/thanks-for-the-testing-help-conclusions/
A simple offset will work, you just need to offset from UTC.
Using datetime you can get the current utc (gmt) time and use datetime objects:
datetime.datetime.utcnow() - Provides time at UTC
datetime.datetime.now() - Provides time at local machine
To get the CT time from any system you need to know the CT time offset from UTC. Then to account for daylight savings time code a function to get the current offset.
>>> import datetime
>>> utc = datetime.datetime.utcnow()
>>> current_ct_offset = get_current_ct_offset()
>>> ct_datetime = utc + datetime.timedelta(hours=current_ct_offset)
I could be overlooking something here, but if your only concerned about one timezone and your not doing tz name handling, it's pretty straight forward.