Skip to content

Instantly share code, notes, and snippets.

@ymyzk
Created April 10, 2015 05:26
Show Gist options
  • Save ymyzk/cedf5a139102cbe53453 to your computer and use it in GitHub Desktop.
Save ymyzk/cedf5a139102cbe53453 to your computer and use it in GitHub Desktop.
Python datetime object <-> Unix time
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import calendar
import datetime
import time
import pytz
# Naive (local time)
now = datetime.datetime.now()
print(now)
# Naive (local time) -> Unix time
unix = int(time.mktime(now.timetuple()))
print(unix)
# Unix time -> Naive (local time)
now = datetime.datetime.fromtimestamp(unix)
print(now)
# Naive (UTC)
now = datetime.datetime.utcnow()
print(now)
# Naive (UTC) -> Unix time
unix = calendar.timegm(now.utctimetuple())
print(unix)
# Unix time -> Naive (UTC)
now = datetime.datetime.utcfromtimestamp(unix)
print(now)
# Aware (UTC)
tz = pytz.utc
now = datetime.datetime.now(tz)
print(now)
# Aware (UTC) -> Unix time
unix = calendar.timegm(now.utctimetuple())
print(unix)
# Unix time -> Aware (UTC)
now = datetime.datetime.fromtimestamp(unix, tz=tz)
print(now)
# Aware (PST)
tz = pytz.timezone("US/Pacific")
now = datetime.datetime.now(tz)
print(now)
# Aware (PST) -> Unix time
unix = calendar.timegm(now.utctimetuple())
print(unix)
# Unix time -> Aware (PST)
now = datetime.datetime.fromtimestamp(unix, tz=tz)
print(now)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment