Generate epoch time

I want to convert my time_stamp string into epoch time but I am not good with datetime and related modules, so getting a little confused. I saw many solutions but none of them had date_time format like mine.

my date_time is in the below format
date_time = "2023-01-1T17:35:19.818"

How can I convert this into epoch time using python?

Any help will be appreciated. Thank you.

>Solution :

With python 3.3+, you can try this:

datetime.datetime.strptime("2023-01-1T17:35:19.818", "%Y-%m-%dT%H:%M:%S.%f").timestamp()
// 1672569319.818

First, I convert your datetime string to datetime.datetime object by using strptime() with your format "%Y-%m-%dT%H:%M:%S.%f".
Then I can just call timestamp() to convert it to epoch time

For older version of python, you can try

(datetime.datetime.strptime("2023-01-1T17:35:19.818", "%Y-%m-%dT%H:%M:%S.%f") - datetime.datetime(1970,1,1)).total_seconds()
// 1672594519.818

I hope it help!

Leave a Reply