Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find time at particular timezone from anywhere

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.

like image 555
hoju Avatar asked Jan 28 '10 05:01

hoju


People also ask

How do you calculate time in different time zones?

Calculating time zones is simple and involves adding or subtracting an hour for every 15 degrees of longitude.

How do I get a specific timezone offset?

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.

How many time zones are there in the world?

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.

What are 7 time zones?

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).


2 Answers

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/

like image 107
Lennart Regebro Avatar answered Oct 18 '22 06:10

Lennart Regebro


You can use time.gmtime() to get time GMT (UTC) from any machine no matter the timezone, then you can apply your offset.

like image 31
Max Shawabkeh Avatar answered Oct 18 '22 06:10

Max Shawabkeh