Search code examples
pythondatetimeutc

exact utc time and localtime converted to utc time are different python


I tried printing the exact UTC time and then tried printing the UTC time by first getting local time and then converting it into UTC time but they had 11 mins difference

Why does this happen and how do I fix this so that I get the correct UTC time that is one printed when I directly get UTC time

from datetime import datetime, tzinfo
import tzlocal
import pytz

local_time =datetime.now()
tz = tzlocal.get_localzone()
print(tz)

utc_time = local_time.replace(tzinfo=tz).astimezone(pytz.utc)
print(utc_time)
correct_utc =datetime.utcnow()
print(correct_utc)

output

Asia/Colombo
2021-07-18 01:54:31.442555+00:00
2021-07-18 01:43:31.619536

I have to make to make a program that takes datetime strings and then convert them into datetime objects and then converts them to utc so using astimezone will be pointless as the program will be running in cloud so it doesnt know the timezone it has to convert from


Solution

  • I think the issue could be in the replace function argument tzinfo=tz. tzinfo is expecting a dateutil.tz.tz.tzfile object and the tz you're passing in is a pytz.tzfile.Asia/Colombo object from the pytz library. You can workaround the issue by instead of using tzinfo=tz, you can convert tz to string type using str(tz) function and then use the function dateutil.tz.gettz to get the timezone's dateutil.tz.tz.tzfile object (tzinfo=dateutil.tz.gettz(str(tz)))

    from datetime import datetime, tzinfo
    import tzlocal
    import pytz
    import dateutil.tz
    
    local_time =datetime.now()
    tz = tzlocal.get_localzone()
    print(tz)
    
    utc_time = local_time.replace(tzinfo=dateutil.tz.gettz(str(tz))).astimezone(pytz.utc)
    print(utc_time)
    correct_utc =datetime.utcnow()
    print(correct_utc)