在 Python 中将字符串日期转换为时间戳
- 2025-02-12 10:04:00
- admin 原创
- 57
问题描述:
如何将格式中的字符串转换"%d/%m/%Y"
为时间戳?
"01/12/2011" -> 1322697600
解决方案 1:
>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0
解决方案 2:
我使用ciso8601
,它比datetime的strptime快62倍。
t = "01/12/2011"
ts = ciso8601.parse_datetime(t)
# to get time in seconds:
time.mktime(ts.timetuple())
您可以在此处了解更多信息。
解决方案 3:
只需使用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()
解决方案 4:
>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200
解决方案 5:
将字符串转换为日期对象:
from datetime import date, datetime
date_string = "01/12/2011"
date_object = date(*map(int, reversed(date_string.split("/"))))
assert date_object == datetime.strptime(date_string, "%d/%m/%Y").date()
将日期对象转换为 POSIX 时间戳的方式取决于时区。来自在 Python 中转换datetime.date
为 UTC 时间戳:
日期对象表示 UTC 午夜
import calendar
timestamp1 = calendar.timegm(utc_date.timetuple())
timestamp2 = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
assert timestamp1 == timestamp2
日期对象表示当地时间的午夜
import time
timestamp3 = time.mktime(local_date.timetuple())
assert timestamp3 != timestamp1 or (time.gmtime() == time.localtime())
除非 UTC 和当地时间的午夜是同一时间实例,否则时间戳会不同。
解决方案 6:
答案还取决于您输入的日期时区。如果您的日期是本地日期,那么您可以像 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
解决方案 7:
我会给初学者(像我一样)一个答案:
您有日期字符串"01/12/2011"
。然后可以按照格式写入"%d/%m/%Y"
。如果您想格式化为其他格式,例如"July 9, 2015"
,这里有一个很好的备忘单。
导入
datetime
库。使用
datetime.datetime
该类来处理日期和时间组合。使用该
strptime
方法将字符串日期时间转换为对象日期时间。最后,使用该
timestamp
方法获取 Unix 纪元时间作为浮点数。因此,
import datetime
print( int( datetime.datetime.strptime( "01/12/2011","%d/%m/%Y" ).timestamp() ) )
# prints 1322712000
解决方案 8:
很多答案都没有考虑到约会本身就很幼稚
为了正确,您需要首先将简单日期设为可感知时区的日期时间
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
还:
请注意,对于许多时区,在 a 中使用pytz
for不起作用。请参阅带有 pytz 时区的 datetime。不同的偏移量取决于 tzinfo 的设置方式tzinfo
`datetime.datetime`
# 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
解决方案 9:
首先,您必须使用strptime类将字符串转换为 struct_time 格式。
然后只需使用mktime即可获取浮点数。
解决方案 10:
我建议使用dateutil:
import dateutil.parser
dateutil.parser.parse("01/12/2011", dayfirst=True).timestamp()
解决方案 11:
看起来相当有效:
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 次循环)
解决方案 12:
您可以转换为 isoformat
my_date = '2020/08/08'
my_date = my_date.replace('/','-') # just to adapte to your question
date_timestamp = datetime.datetime.fromisoformat(my_date).timestamp()
解决方案 13:
最简单的方法
from datetime import datetime
s = "01/12/2011"
sec = datetime.strptime(s,"%d/%m/%Y").timestamp()
如果你想使用时区
from django.utils import timezone
from datetime import datetime
s = "01/12/2011"
sec=datetime.strptime(s,"%d/%m/%Y").replace(tzinfo=timezone.utc).timestamp())
解决方案 14:
您可以参考以下链接使用strptime
函数datetime.datetime
来转换任何格式的日期以及时区。
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
解决方案 15:
一个获取 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
解决方案 16:
只需使用 datetime.timestamp(您的 datetime 实例),datetime 实例包含时区信息,因此时间戳将是标准的 utc 时间戳。如果将 datetime 转换为 timetuple,它将丢失时区,因此结果将是错误的。如果您想提供一个接口,您应该这样写:int(datetime.timestamp(time_instance)) * 1000
解决方案 17:
您可以双向前往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) ) & \n ( time.mktime(the_date.timetuple()) == unix_time )