Reputation: 49
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.
Upvotes: 1
Views: 45
Reputation: 1986
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()
Upvotes: 1
Reputation: 1284
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
Upvotes: 1