【问题标题】:Python How to check the string is a UTC timestamp?Python如何检查字符串是UTC时间戳?
【发布时间】:2021-05-14 08:28:52
【问题描述】:

我需要检查时间戳字符串是否属于'UTC'时间戳

我有以下代码

def time_stamp():
    utc = timezone('UTC')
    time_stamp = datetime.now(utc)
    utc_time_stmap = time_stamp.strftime("%Y-%m-%dT%H:%M:%S.%f")
    return utc_time_stmap

上述函数以字符串格式返回UTC时间

print(type(time_stamp()))
<class 'str'>

print(time_stamp())
'2021-02-10 15:49:57.906168'

“time_stamp()”返回“字符串类型”的时间戳。

#预期:

我需要检查返回值是否在严格的日期 UTC 日期范围内?

感谢您的帮助?

谢谢

【问题讨论】:

  • 该字符串中没有时区信息。你所问的(凭空创造信息)是不可能的(至少在编程领域)
  • 能否请您澄清一下:“utc 日期时间格式”是什么意思? ISO 8601? 2021-02-10 15:49:57.906168 这样的字符串既没有时区信息也没有 UTC 偏移量,你如何确定它是否代表 UTC?
  • 嗨 Pranva 和 MrFuppes,我已经更新了预期的问题,我需要检查返回时间戳是当前 utc 时间戳..

标签: python-3.x datetime datetime-format python-datetime pytz


【解决方案1】:

这里有一些代码,您可以在其中找到答案。

import re
from datetime import datetime

DATETIME_ISO8601 = re.compile(
    r'^([0-9]{4})' r'-' r'([0-9]{1,2})' r'-' r'([0-9]{1,2})' # date
    r'([T\s][0-9]{1,2}:[0-9]{1,2}:?[0-9]{1,2}(\.[0-9]{1,6})?)?' # time
    r'((\+[0-9]{2}:[0-9]{2})| UTC| utc)?' # zone
)

def datetime_iso(string):
    """ verify rule
    Mandatory is: 'yyyy-(m)m-(d)dT(h)h:(m)m'        
    """
    string = string.strip()
    return bool(re.fullmatch(DATETIME_ISO8601, string))

def utc_timezone(datetime_string):
    datetime_string = datetime_string.strip()
    return datetime_string.endswith("00:00") or datetime_string.upper().endswith("UTC")


check_this = ["2020-1-1 22:11", "2020-1-1 22:11:34 00:00", "2020-1-1 22:11:34+00:00", "2020-1-1 22:11+01:00", "2020-1-1 22:11 UTC", "does this help?"]

for datetime_string in check_this:
    print(".........................")
    print(f"This date time string '{datetime_string}' is in datetime iso format: {datetime_iso(datetime_string)}")
    if datetime_iso(datetime_string):
        print(f"Is it the UTC time zone? {utc_timezone(datetime_string)}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 2019-03-14
    • 2021-03-12
    • 2015-12-19
    相关资源
    最近更新 更多