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.
Calculating time zones is simple and involves adding or subtracting an hour for every 15 degrees of longitude.
The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.
To facilitate this, the world has been divided into 24 time zones. These time zones have been created with reference to the Prime Meridian itself.
From east to west they are Atlantic Standard Time (AST), Eastern Standard Time (EST), Central Standard Time (CST), Mountain Standard Time (MST), Pacific Standard Time (PST), Alaskan Standard Time (AKST), Hawaii-Aleutian Standard Time (HST), Samoa standard time (UTC-11) and Chamorro Standard Time (UTC+10).
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/
You can use time.gmtime()
to get time GMT (UTC) from any machine no matter the timezone, then you can apply your offset.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With