我有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)。

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


当前回答

解决方案是

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

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

其他回答

当转换为unix时间戳时,python基本上是假设UTC,但在转换回来时,它会给你一个转换为本地时区的日期。

请看这个问题/答案; 获取datetime.datetime.fromtimestamp()使用的时区

如果你想将python datetime转换为seconds since epoch,你应该显式地做:

>>> import datetime
>>> datetime.datetime(2012, 04, 01, 0, 0).strftime('%s')
'1333234800'
>>> (datetime.datetime(2012, 04, 01, 0, 0) - datetime.datetime(1970, 1, 1)).total_seconds()
1333238400.0

在Python 3.3+中,您可以使用timestamp()来代替:

>>> import datetime
>>> datetime.datetime(2012, 4, 1, 0, 0).timestamp()
1333234800.0
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。

使用UTC时区:

time_stamp = calendar.timegm(dt.timetuple())

datetime.utcfromtimestamp(time_stamp)
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)