2011-07-19

[python] datetime から unix epoch を得る

Python 2.5 で、datetime から、JavaScript で使いやすいミリ秒で表した UNIX 時刻を作る方法を考えてみました。

# coding=utf-8
import time, calendar, datetime, pprint

def datetime_to_epoch_1(dt):
    return int(time.mktime(dt.timetuple())) * 1000 + int(dt.microsecond / 1e3)

def datetime_to_epoch_1_utc(dt):
    return int(calendar.timegm(dt.timetuple())) * 1000 + int(dt.microsecond / 1e3)

def datetime_to_epoch_2(dt):
    delta = dt - datetime.datetime.fromtimestamp(0)
    return delta.days * 86400000 + delta.seconds * 1000 + int(delta.microseconds / 1e3)

def datetime_to_epoch_2_utc(dt):
    delta = dt - datetime.datetime.utcfromtimestamp(0)
    return delta.days * 86400000 + delta.seconds * 1000 + int(delta.microseconds / 1e3)

pp = pprint.PrettyPrinter()
now_local = datetime.datetime.now()
now_utc = datetime.datetime.utcnow()

pp.pprint([
    datetime_to_epoch_1(now_local),
    datetime_to_epoch_2(now_local),
    datetime_to_epoch_1_utc(now_utc),
    datetime_to_epoch_2_utc(now_utc),
    time.time(),
])
# [1311003732034L,
#  1311003732034L,
#  1311003732034L,
#  1311003732034L,
#  1311003732.0339999]