Skip to content

Instantly share code, notes, and snippets.

@danielbushman
Last active August 29, 2015 14:05
Show Gist options
  • Save danielbushman/0e888a36bd264ba58c06 to your computer and use it in GitHub Desktop.
Save danielbushman/0e888a36bd264ba58c06 to your computer and use it in GitHub Desktop.
Make any Python datetime object into a UTC based time-zone-naive datetime. Makes it easier to use UTC everywhere. Makes the bold assumption that anything without time-zone information is already UTC.
import isodate
def make_datetime_naive_utc(dt):
delta = dt.tzinfo.utcoffset(dt) if dt.tzinfo else None
naive_dt = dt.replace(tzinfo=None)
return naive_dt if not delta else naive_dt - delta
local_time_with_tzinfo = isodate.parse_datetime('2014-08-20T14:40:18-06:00')
utc_with_tzinfo = isodate.parse_datetime('2014-08-20T20:40:18Z')
naive_utc = isodate.parse_datetime('2014-08-20T20:40:18')
f = make_datetime_naive_utc
assert f(local_time_with_tzinfo) == f(utc_with_tzinfo) == f(naive_utc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment