Skip to content

Instantly share code, notes, and snippets.

@johndrinkwater
Last active January 11, 2016 16:45
Show Gist options
  • Save johndrinkwater/1af5cca3b392f6cb558c to your computer and use it in GitHub Desktop.
Save johndrinkwater/1af5cca3b392f6cb558c to your computer and use it in GitHub Desktop.
Kinda confused on how messed Python datetime handling is, as I am importing strings and wanting to convert them to UTC, before potentially then outputting to users local tz
# mydate is loaded via yaml.load() from a blob of yaml on the next line
# Date: 2011-02-11 14:23:01
print mydate, 'offset: ', mydate.utcoffset()
# astimezone() called here outputs ValueError: astimezone() cannot be applied to a naive datetime
mydate = mydate.replace( tzinfo=pytz.timezone( 'Europe/London' ) )
print mydate, 'offset: ', mydate.utcoffset()
print mydate.astimezone(pytz.utc)
# outputs
2011-02-12 14:23:01 offset: None
2011-02-12 14:23:01-00:01 offset: -1 day, 23:59:00
2011-02-12 14:24:01+00:00
@johndrinkwater
Copy link
Author

Right, how to fix:

mylocaltz = pytz.timezone( 'Europe/London' )

# What we expect the timezone to be ( global, sorry )
mydate = mylocaltz.localize( mydate )
# Then convert to UTC native
mydate = mydate.astimezone( pytz.utc )  

… and then you discover, yaml.load() strips hour offsets by normalising datetime into UTC, just doesn’t set the tzinfo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment