简体   繁体   English

确切的UTC时间和转换为UTC时间的本地时间是不同的python

[英]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我尝试打印确切的 UTC 时间,然后尝试通过首先获取本地时间然后将其转换为 UTC 时间来打印 UTC 时间,但它们有 11 分钟的差异

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为什么会发生这种情况,我该如何解决这个问题,以便在我直接获得 UTC 时间时获得正确的 UTC 时间

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我必须制作一个接受日期时间字符串的程序,然后将它们转换为日期时间对象,然后将它们转换为 utc,因此使用 astimezone 将毫无意义,因为该程序将在云中运行,因此它不知道它必须转换的时区

I think the issue could be in the replace function argument tzinfo=tz .我认为问题可能出在replace函数参数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. tzinfo期待dateutil.tz.tz.tzfile对象,而您传入​​的tz是来自pytz库的pytz.tzfile.Asia/Colombo对象。 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)) )您可以通过代替使用tzinfo=tz来解决此问题,您可以使用str(tz)函数将tz转换为字符串类型,然后使用函数dateutil.tz.gettz来获取时区的dateutil.tz.tz.tzfile对象( 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM