Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save simonw/857786 to your computer and use it in GitHub Desktop.

Select an option

Save simonw/857786 to your computer and use it in GitHub Desktop.
Convert a local datetime object to a UTC string represestation, taking daylight savings time in to account
"""
Convert a local datetime object to a UTC string represestation, taking
daylight savings time in to account. Here's an example - the clocks change
at 2am on March 13th 2011.
>>> to_utc_datestring(datetime.datetime(2011, 3, 11, 17, 30))
'20110311T233000Z'
>>> to_utc_datestring(datetime.datetime(2011, 3, 15, 17, 30))
'20110315T223000Z'
You can use http://www.timezoneconverter.com/cgi-bin/tzc.tzc to check results
"""
import pytz # http://pytz.sourceforge.net/
def to_utc_datestring(localtime, timezone='America/Chicago'):
tz = pytz.timezone(timezone)
return (localtime.replace(
tzinfo = tz
).astimezone(
pytz.utc
) - tz.dst(localtime)).strftime(
'%Y%m%dT%H%M%SZ'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment