将 python 感知日期时间转换为本地时间元组
Convert python aware datetime to local timetuple
我有一个知道的 datetime
对象:
dt = datetime.datetime.now(pytz.timezone('Asia/Ho_Chi_Minh'))
我正在使用它来将对象转换为时间戳,它目前运行良好:
int(time.mktime(dt.utctimetuple()))
但根据 time docs,time.mktime
需要本地 timetuple
,而不是 UTC timetuple
。如何从 aware datetime
获取本地 timetuple
?或者有没有其他方法可以使 timestamp
而不是 time.mktime
?
我看过这个问题,看来我应该使用calendar.timegm(dt.utctimetuple())
。
Converting datetime to unix timestamp
看来你对自己想要什么感到困惑。
根据您的评论,答案在 python datetime
文档中:
There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc:
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
or by calculating the timestamp directly:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
如果您知道日期时间,则可以通过减去 UTC 纪元的日期时间将其转换为 unix 纪元时间戳,例如:
代码:
import datetime as dt
import pytz
def aware_to_epoch(aware):
# get a datetime that is equal to epoch in UTC
utc_at_epoch = pytz.timezone('UTC').localize(dt.datetime(1970, 1, 1))
# return the number of seconds since epoch
return (aware - utc_at_epoch).total_seconds()
aware = dt.datetime.now(pytz.timezone('Asia/Ho_Chi_Minh'))
print(aware_to_epoch(aware))
结果:
1521612302.341014
我有一个知道的 datetime
对象:
dt = datetime.datetime.now(pytz.timezone('Asia/Ho_Chi_Minh'))
我正在使用它来将对象转换为时间戳,它目前运行良好:
int(time.mktime(dt.utctimetuple()))
但根据 time docs,time.mktime
需要本地 timetuple
,而不是 UTC timetuple
。如何从 aware datetime
获取本地 timetuple
?或者有没有其他方法可以使 timestamp
而不是 time.mktime
?
我看过这个问题,看来我应该使用calendar.timegm(dt.utctimetuple())
。
Converting datetime to unix timestamp
看来你对自己想要什么感到困惑。
根据您的评论,答案在 python datetime
文档中:
There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc:
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
or by calculating the timestamp directly:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
如果您知道日期时间,则可以通过减去 UTC 纪元的日期时间将其转换为 unix 纪元时间戳,例如:
代码:
import datetime as dt
import pytz
def aware_to_epoch(aware):
# get a datetime that is equal to epoch in UTC
utc_at_epoch = pytz.timezone('UTC').localize(dt.datetime(1970, 1, 1))
# return the number of seconds since epoch
return (aware - utc_at_epoch).total_seconds()
aware = dt.datetime.now(pytz.timezone('Asia/Ho_Chi_Minh'))
print(aware_to_epoch(aware))
结果:
1521612302.341014