Warm tip: This article is reproduced from stackoverflow.com, please click
python python-3.x

Convert different date strings to unix timestamp in python 3.6

发布于 2020-03-27 10:23:04

I have two strings. How can I convert them to UNIX timestamp (eg.: "1284101485")? (Please observe that 1284101485 is not the correct answer for this case.)

I don't care about time zones as long as it is consistent.

string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'   
string_2_to_convert = '2019-06-25 13:53:58'
Questioner
Filip Eriksson
Viewed
51
Bilesh Ganguly 2019-07-03 23:16

You can use dateparser

Install:

$ pip install dateparser

Sample code:

import dateparser
from time import mktime

string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'
string_2_to_convert = '2019-06-25 13:53:58'

datetime1 = dateparser.parse(string_1_to_convert)
datetime2 = dateparser.parse(string_2_to_convert)

unix_secs_1 = mktime(datetime1.timetuple())
unix_secs_2 = mktime(datetime2.timetuple())

print(unix_secs_1)
print(unix_secs_2)

Output:

1561492438.0
1561488838.0

The above implementation gives you a consistent response and doesn't give you an error when trying to parse CEST.