How can I convert a day, DD-MM-YYYY HH:MM:SS +XXXX to unix time in Python?

180 Views Asked by At

I'm working with a timestamp that is formatted Thu, 04 Jan 2024 18:25:01 +0000 but I need it in Unix time. I've looked at several library functions and cannot figure out how I can achieve this. How can I convert this to a unix timestamp?

I looked at the different Python datetime methods and none of them would achieve my goal.

1

There are 1 best solutions below

1
azro On

Use datetime.timestamp that gives UNIX timestamp, in seconds, precision of microseconds

Use datetime.strptime to convert a string to a datetime object

from datetime import datetime

d = datetime.now()
print(d.timestamp(), "seconds")  # 1704394088.831857 seconds

d = datetime.strptime("Thu, 04 Jan 2024 18:25:01 +0000", "%a, %d %b %Y %H:%M:%S %z")
print(d.timestamp(), "seconds")  # 1704392701.0
print(datetime.utcfromtimestamp(d.timestamp()))  # 2024-01-04 18:25:01