Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - strtotime equivalent?

Tags:

python

I'm using this to convert date time strings to a unix timestamp:

str(int(time.mktime(time.strptime(date,"%d %b %Y %H:%M:%S %Z"))))

However often the date structure isn't the same so I keep getting the following error message:

time data did not match format: data=Tue, 26 May 2009 19:58:20 -0500 fmt=%d %b %Y %H:%M:%S %Z

Does anyone know of any simply function to convert a string representation of a date/time to a unix timestamp in python? I really don't want to have to open a process to call a php script to echo the timestamp everytime time in a loop :)

like image 837
Joe Avatar asked Oct 08 '10 20:10

Joe


People also ask

How do I convert a string to a timestamp in Python?

Import the datetime library. Use the datetime. datetime class to handle date and time combinations. Use the strptime method to convert a string datetime to a object datetime.

How do you convert string to UTC time in Python?

Python convert a string to datetime with timezone In this example, I have imported a module called timezone. datetime. now(timezone('UTC')) is used to get the present time with timezone. The format is assigned as time = “%Y-%m-%d %H:%M:%S%Z%z”.

How do I convert a string to a date in Python?

parse() can be used to convert a string into date-time format. The only parameter used is the string.


1 Answers

from dateutil.parser import parse

parse('Tue, 26 May 2009 19:58:20 -0500').strftime('%s')

# returns '1243364300'
like image 136
eumiro Avatar answered Oct 03 '22 22:10

eumiro