Skip to content

Instantly share code, notes, and snippets.

@hdemers
Created April 14, 2013 17:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hdemers/5383522 to your computer and use it in GitHub Desktop.
Save hdemers/5383522 to your computer and use it in GitHub Desktop.
I never remember how to convert to/from UTC datetime and epoch. Now I don't have to.
"""UTC time conversion functions.
"""
from calendar import timegm
from datetime import datetime
def utcdt2epoch(utcdatetime):
"""Convert a datetime object expressed in UTC to a Unix timestamp expressed
in seconds since the epoch (Jan 1st 1970).
"""
return timegm(utcdatetime.timetuple())
def epoch2utcdt(epoch):
"""Convert a Unix timestamp expressed in seconds since the epoch (Jan 1st
1970) to a datetime object expressed in UTC.
"""
return datetime.utcfromtimestamp(epoch)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment