我有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)
其他回答
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())
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'