Convert string date to timestamp in Python

匿名 (未验证) 提交于 2019-12-03 02:13:02

问题:

How to convert a string in the format "%d/%m/%Y" to timestamp?

"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:

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. From Converting datetime.date to UTC timestamp in Python:

  • date object represents midnight in 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.



回答3:

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


回答4:

i use ciso8601 which is 62x faster than datetime's strptime.

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

you can learn more at here



回答5:

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:

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

Now if the input date is already in UTC, than I believe the right solution is:

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


回答6:

First you must the strptime class to convert the string to a struct_time format.

Then just use mktime from there to get your float.



回答7:

I would suggest dateutil:

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


回答8:

just use datetime.timestamp(your datetime instanse), datetime instance contains the timezone infomation, so the timestamp will be a standard utc timestamp. 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



回答9:

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=)  # convert to UTC timezone utc = pytz.UTC d = d.astimezone(utc) >>> datetime.datetime(2011, 12, 1, 8, 0, tzinfo=)  # 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=)  # 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. See datetime with pytz timezone. Different offset depending on how tzinfo is set

# 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=) # 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=) # you end up with an offset 

https://en.wikipedia.org/wiki/Local_mean_time



回答10:

Seems to be quite efficient:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!