简体   繁体   English

将字符串日期转换为 Python 中的时间戳

[英]Convert string date to timestamp in Python

How to convert a string in the format "%d/%m/%Y" to timestamp?如何将格式为"%d/%m/%Y"的字符串转换为时间戳?

"01/12/2011" -> 1322697600
>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0

I use ciso8601 , which is 62x faster than datetime's strptime.我使用ciso8601 ,它比 datetime 的 strptime 快 62 倍。

t = "01/12/2011"
ts = ciso8601.parse_datetime(t)
# to get time in seconds:
time.mktime(ts.timetuple())

You can learn more here .您可以在此处了解更多信息

To convert the string into a date object:要将字符串转换为日期对象:

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()

The way to convert the date object into POSIX timestamp depends on timezone.将日期对象转换为 POSIX 时间戳的方式取决于时区。 From Converting datetime.date to UTC timestamp in Python :在 Python 中将datetime.date转换为 UTC 时间戳

  • date object represents midnight in 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
  • date object represents midnight in local time日期对象表示当地时间的午夜

    import time timestamp3 = time.mktime(local_date.timetuple()) assert timestamp3 != timestamp1 or (time.gmtime() == time.localtime())

The timestamps are different unless midnight in UTC and in local time is the same time instance.时间戳是不同的,除非 UTC 和本地时间的午夜是相同的时间实例。

>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200

The answer depends also on your input date timezone.答案还取决于您输入的日期时区。 If your date is a local date, then you can use mktime() like katrielalex said - only I don't see why he used datetime instead of this shorter version:如果您的日期是本地日期,那么您可以像 katrielalex 所说的那样使用 mktime() - 只有我不明白他为什么使用 datetime 而不是这个较短的版本:

>>> time.mktime(time.strptime('01/12/2011', "%d/%m/%Y"))
1322694000.0

But observe that my result is different than his, as I am probably in a different TZ (and the result is timezone-free UNIX timestamp)但请注意,我的结果与他的不同,因为我可能处于不同的 TZ(结果是无时区的 UNIX 时间戳)

Now if the input date is already in UTC, than I believe the right solution is:现在,如果输入日期已经是 UTC,那么我相信正确的解决方案是:

>>> calendar.timegm(time.strptime('01/12/2011', '%d/%m/%Y'))
1322697600

Simply use datetime.datetime.strptime :只需使用datetime.datetime.strptime

import datetime
stime = "01/12/2011"
print(datetime.datetime.strptime(stime, "%d/%m/%Y").timestamp())

Result:结果:

1322697600

To use UTC instead of the local timezone use .replace :要使用 UTC 而不是本地时区,请使用.replace

datetime.datetime.strptime(stime, "%d/%m/%Y").replace(tzinfo=datetime.timezone.utc).timestamp()

A lot of these answers don't bother to consider that the date is naive to begin with很多这些答案都没有考虑到日期是天真的开始

To be correct, you need to make the naive date a timezone aware datetime first为了正确起见,您需要先将天真日期设为时区感知日期时间

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

Also:还:

Be careful, using pytz for tzinfo in a datetime.datetime DOESN'T WORK for many timezones.小心,在datetime.datetimetzinfo使用pytz对许多时区pytz See datetime with pytz timezone. 使用 pytz 时区查看日期时间。 Different offset depending on how tzinfo is set 不同的偏移量取决于 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 https://en.wikipedia.org/wiki/Local_mean_time

I would suggest dateutil :我建议dateutil

import dateutil.parser
dateutil.parser.parse("01/12/2011", dayfirst=True).timestamp()

First you must the strptime class to convert the string to a struct_time format.首先,您必须使用strptime类将字符串转换为 struct_time 格式。

Then just use mktime from there to get your float.然后从那里使用mktime来获得你的浮动。

Seems to be quite efficient:似乎非常有效:

import datetime
day, month, year = '01/12/2011'.split('/')
datetime.datetime(int(year), int(month), int(day)).timestamp()

1.61 µs ± 120 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)每个循环 1.61 µs ± 120 ns(7 次运行的平均值 ± 标准偏差,每次 100000 次循环)

you can convert to isoformat你可以转换成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()

You can refer this following link for using strptime function from datetime.datetime , to convert date from any format along with time zone.您可以参考以下链接以使用来自datetime.datetime strptime函数,将日期与时区一起从任何格式转换。

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

just use datetime.timestamp(your datetime instanse), datetime instance contains the timezone infomation, so the timestamp will be a standard utc timestamp.只需使用 datetime.timestamp(your datetime instanse),datetime 实例包含时区信息,因此时间戳将是标准的 utc 时间戳。 if you transform the datetime to timetuple, it will lose it's timezone, so the result will be error.如果将日期时间转换为时间元组,它将丢失其时区,因此结果将是错误的。 if you want to provide an interface, you should write like this: int(datetime.timestamp(time_instance)) * 1000如果你想提供一个接口,你应该这样写: int(datetime.timestamp(time_instance)) * 1000

A simple function to get UNIX Epoch time.获取 UNIX Epoch 时间的简单函数。

NOTE : This function assumes the input date time is in UTC format (Refer to comments here).注意:此函数假定输入日期时间为 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())

Usage :用法

>>> utctimestamp("01/12/2011")
1322697600
>>> utctimestamp("2011-12-01", "%Y-%m-%d")
1322697600

I would give a answer for beginners (like me):我会给初学者(像我一样)一个答案:

You have the date string "01/12/2011" .您有日期字符串"01/12/2011" Then it can be written by the format "%d/%m/%Y" .然后它可以通过格式"%d/%m/%Y"写入。 If you want to format to another format like "July 9, 2015" , here a good cheatsheet.如果您想格式化为另一种格式,例如"July 9, 2015"这里有一个很好的备忘单。

  • Import the datetime library.导入datetime库。

  • Use the datetime.datetime class to handle date and time combinations.使用datetime.datetime类来处理日期和时间组合。

  • Use the strptime method to convert a string datetime to a object datetime.使用strptime方法将字符串日期时间转换为对象日期时间。

  • Finally, use the timestamp method to get the Unix epoch time as a float.最后,使用timestamp方法以浮点数形式获取 Unix 纪元时间。 So,所以,

import datetime
print( int( datetime.datetime.strptime( "01/12/2011","%d/%m/%Y" ).timestamp() ) )

# prints 1322712000

You can go both directions , unix epoch <==> datetime :你可以双向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         )   

all of these examples have a static date, is there an example when we need todays date or the current date?所有这些示例都有一个 static 日期,是否有我们需要今天日期或当前日期的示例?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM