如何将格式为“%d/%m/%Y”的字符串转换为时间戳?
"01/12/2011" -> 1322697600
如何将格式为“%d/%m/%Y”的字符串转换为时间戳?
"01/12/2011" -> 1322697600
当前回答
>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200
其他回答
答案也取决于你输入的日期和时区。如果你的日期是本地日期,那么你可以像katrielalex说的那样使用mktime() -只是我不明白为什么他使用datetime而不是这个更短的版本:
>>> time.mktime(time.strptime('01/12/2011', "%d/%m/%Y"))
1322694000.0
但是请注意,我的结果与他的结果不同,因为我可能在不同的TZ中(结果是无时区的UNIX时间戳)
现在如果输入日期已经是UTC,那么我认为正确的解决方案是:
>>> calendar.timegm(time.strptime('01/12/2011', '%d/%m/%Y'))
1322697600
似乎相当有效:
import datetime
day, month, year = '01/12/2011'.split('/')
datetime.datetime(int(year), int(month), int(day)).timestamp()
1.61µs±120 ns /循环(7次运行的平均值±标准值,每次100000次循环)
使用datetime即可。时间戳(您的datetime实例),datetime实例包含时区信息,因此时间戳将是标准utc时间戳。如果您将datetime转换为timetuple,它将失去它的时区,因此结果将是错误的。 如果你想提供一个接口,你应该这样写: Int (datetime.timestamp(time_instance)) * 1000
很多答案都没有考虑到日期一开始就很天真
为了正确,您需要首先将初始日期设置为具有时区意识的datetime
import datetime
import pytz
# naive datetime
d = datetime.datetime.strptime('01/12/2011', '%d/%m/%Y')
>>> datetime.datetime(2011, 12, 1, 0, 0)
# add proper timezone
pst = pytz.timezone('America/Los_Angeles')
d = pst.localize(d)
>>> datetime.datetime(2011, 12, 1, 0, 0,
tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
# convert to UTC timezone
utc = pytz.UTC
d = d.astimezone(utc)
>>> datetime.datetime(2011, 12, 1, 8, 0, tzinfo=<UTC>)
# epoch is the beginning of time in the UTC timestamp world
epoch = datetime.datetime(1970,1,1,0,0,0,tzinfo=pytz.UTC)
>>> datetime.datetime(1970, 1, 1, 0, 0, tzinfo=<UTC>)
# get the total second difference
ts = (d - epoch).total_seconds()
>>> 1322726400.0
另外:
小心,在datetime中使用pytz for tzinfo。datetime不适用于许多时区。参见datetime with pytz timezone。不同的偏移量取决于tzinfo的设置方式
# Don't do this:
d = datetime.datetime(2011, 12, 1,0,0,0, tzinfo=pytz.timezone('America/Los_Angeles'))
>>> datetime.datetime(2011, 1, 12, 0, 0,
tzinfo=<DstTzInfo 'America/Los_Angeles' LMT-1 day, 16:07:00 STD>)
# tzinfo in not PST but LMT here, with a 7min offset !!!
# when converting to UTC:
d = d.astimezone(pytz.UTC)
>>> datetime.datetime(2011, 1, 12, 7, 53, tzinfo=<UTC>)
# you end up with an offset
https://en.wikipedia.org/wiki/Local_mean_time
你可以从两个方向,unix epoch <==> datetime:
import datetime
import time
the_date = datetime.datetime.fromtimestamp( 1639763585 )
unix_time = time.mktime(the_date.timetuple())
assert ( the_date == datetime.datetime.fromtimestamp(unix_time) ) & \
( time.mktime(the_date.timetuple()) == unix_time )