Login

Converting PDT to UTC using pytz and dateutil

Author:
simon
Posted:
August 21, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

Every time I have to do this it takes me a solid half hour to figure it out, so I'm throwing it up here for future reference. I hate timezone calculations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import pytz
import dateutil.parser

TZINFOS = {
    'PDT': pytz.timezone('US/Pacific'),
    # ... add more to handle other timezones
    # (I wish pytz had a list of common abbreviations)
}

datestring = '11:45:00 Aug 13, 2008 PDT'

# Parse the string using dateutil
datetime_in_pdt = dateutil.parser.parse(datestring, tzinfos= TZINFOS)

# t is now a PDT datetime; convert it to UTC
datetime_in_utc = datetime_in_pdt.astimezone(pytz.utc)

# Let's convert it to a naive datetime object
datetime_naive = datetime_in_utc.replace(tzinfo = None)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Klortho (on May 12, 2017):

This is great, and I'd note that it suggests how to parse date strings that don't have timezone info, but for which the timezone is known. For example, if you access a service on the US east coast, and it is known to respond with datetime strings in local time, but without an explicit tz suffix, you can parse it with:

datestring = '2017-05-09T14:12:11'   # given this
TZINFOS = { 'FOO': pytz.timezone('US/Eastern') }
dt_east = dateutil.parser.parse(datestring + ' FOO', tzinfos = TZINFOS)
...

This does not rely at all on the local machine's timezone, so should work wherever it runs. I'd love to hear if there's an easier way.

#

Please login first before commenting.