How to convert current time from a specific format to epoch time in python?

Question:

My current time format is in "Wednesday, November 16, 2022 4:21:33.082 PM GMT+05:30" format.

How can I convert this to epoch time using python?

Here in this case the epoch time should be "1668595893082"

Note: I always want to get my current time format in the above format and then convert that to epoch.

Please guide me.

I tried using strftime(‘%s’) but could not get the solution. Its throwing invalid format exception.

Asked By: Asit Sahoo

||

Answers:

I have used dateutil in the past, it can parse textual dates into datetime.datetime objects (from the inbuilt datetime package)

First you need to install it:

pip install python-dateutil

Then you can use it like so:

from dateutil import parser

# extract datetime object from string
dttm = parser.parse('Wednesday, November 16, 2022 4:21:33.082 PM GMT+05:30')

# convert to unix time
print(dttm.timestamp())

>>> 1668635493.082
Answered By: Matt
from datetime import datetime

dt_string = "Wednesday, November 16, 2022 4:21:33.082 PM GMT+05:30"
dt_format = '%A, %B %d, %Y %I:%M:%S.%f %p GMT%z'
datetime.strptime(dt_string, dt_format).timestamp() * 1_000

See datetime: strftime() and strptime() Format Codes and datetime: datetime.timestamp()

Answered By: Klas Š.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.