我有dt = datetime(2013,9,1,11),我想获得这个datetime对象的Unix时间戳。

当我做(dt - datetime(1970,1,1)).total_seconds()时,我得到了时间戳1378033200。

当转换回使用datetime.fromtimestamp时,我得到了datetime。Datetime(2013, 9,1,6,0)。

时间不对。我错过了什么?


当前回答

如果datetime对象表示UTC时间,则不要使用time。Mktime,因为它假设元组在您的本地时区。相反,使用calendar.timegm:

>>> import datetime, calendar
>>> d = datetime.datetime(1970, 1, 1, 0, 1, 0)
>>> calendar.timegm(d.timetuple())
60

其他回答

import time
from datetime import datetime
time.mktime(datetime.now().timetuple())

解决方案是

import time
import datetime
d = datetime.date(2015,1,5)

unixtime = time.mktime(d.timetuple())

如果datetime对象表示UTC时间,则不要使用time。Mktime,因为它假设元组在您的本地时区。相反,使用calendar.timegm:

>>> import datetime, calendar
>>> d = datetime.datetime(1970, 1, 1, 0, 1, 0)
>>> calendar.timegm(d.timetuple())
60
def datetime_to_epoch(d1):
"""
January 1st, 1970 at 00:00:00 UTC is referred to as the Unix epoch
:param d1: input date
:return: seconds since unix epoch
"""
if not d1.tzinfo:
    raise ValueError("date is missing timezone information")

d2 = datetime(1970, 1, 1, tzinfo=timezone.utc)
time_delta = d1 - d2
ts = int(time_delta.total_seconds())
return ts


def epoch_to_datetime_string(timestamp, tz_name="UTC", **kwargs):
"""
method to convert unix timestamp to date time string
:param ts: 10 digit unix timestamp in seconds
:param tz_name: timezone name
:param kwargs: formatter=<formatter-string>
:return: date time string in timezone
"""

naive_date = datetime.fromtimestamp(timestamp)
aware_date = naive_date.astimezone(pytz.timezone(tz_name))
formatter = kwargs.pop("formatter", "%d %b %Y %H:%M:%S")
return aware_date.strftime(formatter)
def dt2ts(dt, utc=False):
    if utc:
        return calendar.timegm(dt.timetuple())
    if dt.tzinfo is None:
        return int(time.mktime(dt.timetuple()))
    utc_dt = dt.astimezone(tz.tzutc()).timetuple()
    return calendar.timegm(utc_dt)

如果你想要UTC时间戳:时间。mktime仅用于本地dt。使用日历。Timegm是安全的,但dt必须在utc区域,所以将区域更改为utc。如果dt是UTC,则使用calendar.timegm。