Login

Converting PDT to UTC using pytz and dateutil

Author:
simon
Posted:
August 21, 2008
Language:
Python
Version:
.96
Tags:
utc pytz timezones pdt
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. astimezone template tag by whardier 4 years, 6 months ago
  2. Template tags for localizing UTC times with pytz by wolever 4 years ago
  3. filter dates to user profile's timezone by Scanner 8 years, 4 months ago
  4. UTC-based astimezone filter by miracle2k 3 years, 10 months ago
  5. UTC DateTime field by ludo 8 years ago

Comments

Please login first before commenting.