Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i convert a python local datetime object to utc

I have due_by as a local datetime object the following solutions isn't working for me!

due_by = float(due_by.strftime("%s"))
due_by = datetime.utcfromtimestamp(due_by)

Thanks in advance!

like image 757
Osama Arshad Avatar asked Mar 13 '26 05:03

Osama Arshad


1 Answers

from datetime import datetime
from datetime import timezone

# Datetime to timestamp
t = datetime.now()
due_by = t.timestamp()
# 1600261731.016313
print(due_by)

# Timestamp to datetime
due_by = datetime.fromtimestamp(due_by, tz=timezone.utc)
# 2020-09-16 13:08:51.016313+00:00
print(due_by)
like image 131
Aviv Yaniv Avatar answered Mar 15 '26 17:03

Aviv Yaniv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!