【问题标题】:How to Convert GMT time to Local time如何将格林威治标准时间转换为当地时间
【发布时间】:2020-11-25 13:30:42
【问题描述】:

我是 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)

【问题讨论】:

  • 究竟有什么不适合你?

标签: python datetime utc gmt


【解决方案1】:

这是一种方法,您可以通过 cmets 中的一些解释来做到这一点:

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 对象属于本地时间(操作系统时区设置),如果它是幼稚的(没有时区信息)。
  • 其次,您不能将 naive 日期时间对象(未定义时区/UTC 偏移量)与 aware 日期时间对象(已给出时区信息)进行比较。

[datetime module docs]

【讨论】:

    【解决方案2】:

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

    请注意:正如您在MrFuppes answer 中看到的,您需要谨慎行事。时区意识。但是,如果您将所有时间对象保持在 UTC 中,那么使用 datetime.utcnow() 的简单方法应该没问题。

    【讨论】:

    • 谢谢你,我不知道 - 多么天真;-)
    • 好吧,即使没有 utcnow() 之类的功能,datetime 也足够令人困惑(这使 UTC 变得幼稚,因此也 not UTC...)^^跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 2017-02-11
    • 2020-03-31
    • 2011-05-13
    • 2011-10-30
    相关资源
    最近更新 更多