Search code examples
pythonepoch

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


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.


Solution

  • 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()