我有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)。
时间不对。我错过了什么?
我有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)。
时间不对。我错过了什么?
当前回答
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 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)
使用UTC时区:
time_stamp = calendar.timegm(dt.timetuple())
datetime.utcfromtimestamp(time_stamp)
您错过了时区信息(已回答,同意)
箭包允许避免这种折磨与日期时间;它已经被编写、测试、pypi发布、跨python (2.6 - 3.xx)。
所有你需要的:pip安装箭头(或添加到依赖项)
解决你的问题
dt = datetime(2013,9,1,11)
arrow.get(dt).timestamp
# >>> 1378033200
bc = arrow.get(1378033200).datetime
print(bc)
# >>> datetime.datetime(2013, 9, 1, 11, 0, tzinfo=tzutc())
print(bc.isoformat())
# >>> '2013-09-01T11:00:00+00:00'
当转换为unix时间戳时,python基本上是假设UTC,但在转换回来时,它会给你一个转换为本地时区的日期。
请看这个问题/答案; 获取datetime.datetime.fromtimestamp()使用的时区
与其用这个表达式从dt中创建POSIX时间戳,
(dt - datetime(1970,1,1)).total_seconds()
用这个:
int(dt.strftime("%s"))
我用第二种方法在你的例子中得到了正确答案。
编辑:一些后续…经过一些评论(见下文)后,我对strftime中缺少对%s的支持或文档感到好奇。以下是我的发现:
在datetime和time的Python源代码中,字符串STRFTIME_FORMAT_CODES告诉我们:
"Other codes may be available on your platform.
See documentation for the C library strftime function."
所以现在如果我们使用strftime(在Mac OS X等BSD系统上),你会发现对%s的支持:
"%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3))."
不管怎样,这就是为什么%s在系统中起作用。但是对于OP的问题,有更好的解决方案(将时区考虑在内)。请看@abarnert的接受答案。