datetime 

Send to Kindle
home » snippets » python » datetime



Parsing

Formatting

time.time()

time.ctime([secs])

Epoch Time

When a tuple with an incorrect length is passed to a function expecting a struct_time, or having elements of the wrong type, a TypeError is raised.


Timestamps

import datetime, calendar

# Get current UTC timestamp
def timestamp_utcnow():
  utc_dt = datetime.datetime.utcnow()
  return int(calendar.timegm(utc_dt.utctimetuple()))


Translating between timezones

Translate to Eastern Timezone

import calendar
import datetime
import pytz
import time

now = datetime.datetime.now()
# First, translate to UTC.
now = datetime.datetime.utcfromtimestamp(time.mktime(now.timetuple()))
# Next, stick in the tzinfo to mark it as UTC (pytz requires it.)
now = now.replace(tzinfo=pytz.timezone("UTC"))
# Finally, translate to the target timezone.
now = now.astimezone(pytz.timezone("US/Eastern"))

def parse_utc_timestamp(utc_timestamp):
  date_obj = datetime.datetime.utcfromtimestamp(utc_timestamp)
  # This is needed for any .astimezone() calls done later.
  date_obj = date_obj.replace(tzinfo=pytz.timezone("UTC"))
  return date_obj

def local_to_utc(local_date_obj):
  # Translate to UTC.  We use time.mktime().
  # The parallel function, calendar.timegm(), takes it's
  # input in UTC and not local.
  utc_timestamp = time.mktime(local_date_obj.timetuple())
  return parse_utc_timestamp(utc_timestamp)

def utc_to_eastern(date_obj):
  date_obj = date_obj.astimezone(pytz.timezone("US/Eastern"))
  return date_obj

def utc_to_pacific(date_obj):
  date_obj = date_obj.astimezone(pytz.timezone("US/Pacific"))
  return date_obj


print "Eastern stuff"

now = datetime.datetime.now()
print "local =", now
now_utc = local_to_utc(now)
print "local -> utc =", now_utc
print "utcnow =", datetime.datetime.utcnow()

now_eastern = utc_to_eastern(now_utc)
print now_eastern