Skip to content

Instantly share code, notes, and snippets.

@alexland
Last active March 8, 2018 01:55
Show Gist options
  • Save alexland/94c66c99dfc41ab9f762 to your computer and use it in GitHub Desktop.
Save alexland/94c66c99dfc41ab9f762 to your computer and use it in GitHub Desktop.
various date/time conversions in python
from datetime import datetime as DT
#------------------ epoch time -----------------#
>>> import time
>>> time.time()
1411060580.205373
#------------------ human-friendly string -----------------#
>>> import time
>>> time.ctime()
'Thu Sep 18 10:16:25 2014'
#------------------ convert datetime to epoch time -----------------#
# begin with a string:
s = "2013-08-13 22:06:01"
# convert to a datetime_obj
dt_obj = DT.strptime(s, "%Y-%m-%d %H:%M:%S")
dt_obj
# returns: datetime.datetime(2013, 8, 13, 22, 6, 1)
print(dt_obj)
# returns: 2013-08-13 22:06:01
dt_obj
datetime.datetime(2013, 8, 13, 22, 6, 1)
import calendar
# first convert to a utc timetuple, then to unix timestamp
unix_timestamp = calendar.timegm(date_obj.utctimetuple())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment