【问题标题】:In flask how to get current time in GMT?在烧瓶中如何获得格林威治标准时间的当前时间?
【发布时间】:2015-08-21 08:51:42
【问题描述】:

我想获取格林威治标准时间的当前时间,例如2015-08-21 05:13:13+00:00 在这里您可以看到格林威治标准时间00:00 进行了更正,在django 中,他们使用from django.utils import timezonedate_to = timezone.now() 来计算当前时间。我将如何在烧瓶中获得相同的功能,时间的甲酸盐应该像 2015-08-21 05:13:13+00:00 而不是像 2015-03-30 07:19:06.746037+02。我得到了这个link,但他们正在使用2015-03-30 07:19:06+02。我不想要。只是 GTM 时间

以下代码在 Django 中,我想要在 Flask 中相同,这里他们使用from django.utils import timezone。在 Flask 中是什么等价物,它以这种格式给出当前时间 2015-08-21 05:13:13+00:00

import datetime
import pytz
from django.utils import timezone
def calc_date_args(date_from, date_to, date_options):


        try:
            date_to = timezone.now()
            print 'calc_date_args, date_to', date_to   #calc_date_args, date_to 2015-08-21 05:13:13.615541+00:00

            date_from = date_to - datetime.timedelta(days=float(date_options))

        except Exception:
            raise ValueError(_("The time delta must be a number representing "
                               "the time span in days"))

    return date_from, date_to

【问题讨论】:

    标签: python flask


    【解决方案1】:

    不确定您是否指的是 UTC 时间而不是 GMT,因为大多数机器都使用 UTC 并且大多数时间戳都使用 UTC。

    在 Python 3 中获取 UTC 时区感知时间戳:

    import datetime
    
    def now():
        """Get timezone-aware UTC timestamp."""
        return datetime.datetime.now(datetime.timezone.utc)
    

    【讨论】:

    • 感谢您的回复,我尝试了您的方法,但出现错误Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'timezone'
    • 您的 Python 版本太旧。 datetime.timezone 在 Python 3.3+ 上可用
    猜你喜欢
    • 2011-03-01
    • 1970-01-01
    • 2019-11-25
    • 2010-10-25
    • 2013-03-10
    • 2011-05-13
    • 2011-10-30
    • 1970-01-01
    • 2010-12-02
    相关资源
    最近更新 更多