如何将格式为“%d/%m/%Y”的字符串转换为时间戳?
"01/12/2011" -> 1322697600
如何将格式为“%d/%m/%Y”的字符串转换为时间戳?
"01/12/2011" -> 1322697600
当前回答
我使用ciso8601,它比datetime的strptime快62倍。
t = "01/12/2011"
ts = ciso8601.parse_datetime(t)
# to get time in seconds:
time.mktime(ts.timetuple())
你可以在这里了解更多。
其他回答
一个获取UNIX纪元时间的简单函数。
注意:此函数假设输入日期时间为UTC格式(请参阅此处的注释)。
def utctimestamp(ts: str, DATETIME_FORMAT: str = "%d/%m/%Y"):
import datetime, calendar
ts = datetime.datetime.utcnow() if ts is None else datetime.datetime.strptime(ts, DATETIME_FORMAT)
return calendar.timegm(ts.utctimetuple())
用法:
>>> utctimestamp("01/12/2011")
1322697600
>>> utctimestamp("2011-12-01", "%Y-%m-%d")
1322697600
使用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
您可以从datetime引用下面的链接来使用strptime函数。Datetime,从任何格式转换日期和时区。
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
只需使用datetime.datetime.strptime:
import datetime
stime = "01/12/2011"
print(datetime.datetime.strptime(stime, "%d/%m/%Y").timestamp())
结果:
1322697600
要使用UTC而不是本地时区,请使用.replace:
datetime.datetime.strptime(stime, "%d/%m/%Y").replace(tzinfo=datetime.timezone.utc).timestamp()