如何将GMT时间转换为本地时间

2024-03-28 21:48:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我需要将air_time变量转换为本地机器时间,或将current_time变量转换为GMT,然后在此脚本中从其他变量中减去一个,但不知道如何执行

from datetime import datetime

air_time_GMT = '2020-08-05 13:30:00'
air_time = datetime.strptime(air_time_GMT, '%Y-%m-%d %H:%M:%S')
current_time = datetime.now()

time_remaining = air_time - current_time

print(time_remaining)

Tags: fromimport脚本机器datetimetime时间current
2条回答

您正在查找的命令是datetime.utcnow()。 如果使用此时间而不是datetime.now(),脚本将使用当前GMT时间而不是当前时区/机器时间

请注意:正如您在MrFuppes answer中所看到的,您需要谨慎行事。时区意识。但是,如果您将所有时间对象保持为原始状态并使用UTC,则使用datetime.utcnow()的简单方法应该可以

下面是一种方法,您可以在评论中进行一些解释:

from datetime import datetime, timezone

air_time_GMT = '2020-08-05 13:30:00'

# Python will assume your input is local time if you don't specify a time zone:
air_time = datetime.strptime(air_time_GMT, '%Y-%m-%d %H:%M:%S')
# ...so let's do this:
air_time = air_time.replace(tzinfo=timezone.utc) # using UTC since it's GMT
       
# again, if you don't supply a time zone, you will get a datetime object that
# refers to local time but has no time zone information:
current_time = datetime.now()

# if you want to compare this to a datetime object that HAS time zone information,
# you need to set it here as well. You can set local time zone via
current_time = current_time.astimezone()

print(current_time)
print(air_time-current_time)
>>> 2020-08-05 14:11:45.209587+02:00 # note that my machine is on UTC+2 / CEST
>>> 1:18:14.790413

我想你应该注意两件事

  • 首先,Python默认假定datetime对象属于本地时间(OS时区设置),如果它是原始的(没有时区信息)
  • 其次,您不能将naive日期时间对象(未定义时区/UTC偏移量)与aware日期时间对象(给定时区信息)进行比较

[datetime module docs]

相关问题 更多 >