2

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'

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that's awesome
1

you can use .strptime to parse by a format you specify.

try this:

import datetime

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

ts1 = datetime.datetime.strptime(string_1_to_convert, "%a %b %d %H:%M:%S %Z %Y").timestamp()
ts2 = datetime.datetime.strptime(string_2_to_convert, "%Y-%m-%d %H:%M:%S").timestamp()

print(ts1)
print(ts2)

NOTICE: the CEST part might be non-portable, as strptime only knows how to parse timezones that appear in time.tzname.

1 Comment

I guess this would work if I first remove CEST. However I accepted the solution by Bilesh Ganguly which doesn't require that. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.