Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use timezones with a datetime object in python?

How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()

import datetime, re from datetime import tzinfo  class myTimeZone(tzinfo):     """docstring for myTimeZone"""     def utfoffset(self, dt):         return timedelta(hours=1)  def myDateHandler(aDateString):     """u'Sat,  6 Sep 2008 21:16:33 EDT'"""     _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)')     day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups()     month = [             'JAN', 'FEB', 'MAR',              'APR', 'MAY', 'JUN',              'JUL', 'AUG', 'SEP',              'OCT', 'NOV', 'DEC'     ].index(month.upper()) + 1     dt = datetime.datetime(         int(year), int(month), int(day),          int(hour), int(minute), int(second)     )                        # dt = dt - datetime.timedelta(hours=1)     # dt = dt - dt.tzinfo.utfoffset(myTimeZone())     return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0)  def main():     print myDateHandler("Sat,  6 Sep 2008 21:16:33 EDT")  if __name__ == '__main__':     main() 
like image 767
jidar Avatar asked Sep 22 '08 20:09

jidar


People also ask

How do you make a timezone aware datetime object in Python?

Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.

How do I change the timezone on a datetime object?

The correct way is to use timezone. localize() instead. Using datetime. replace() is OK when working with UTC as shown above because it does not have daylight savings time transitions to deal with.

How do you use time zones in Python?

Use the datetime. astimezone() method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.


2 Answers

I recommend babel and pytz when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezones.

  • Babel
  • pytz
like image 174
Armin Ronacher Avatar answered Oct 19 '22 02:10

Armin Ronacher


The Python standard library doesn't contain timezone information, because unfortunately timezone data changes a lot faster than Python. You need a third-party module for this; the usual choice is pytz

like image 25
Thomas Wouters Avatar answered Oct 19 '22 04:10

Thomas Wouters