如何使用Python检查unicode字符串中是否存在时区

2024-04-26 17:48:33 发布

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

我在JSON数据中有时间戳字段,其中一些时间戳的时间戳格式是str("2014-05-12 00:00:00"),另一个是str("2015-01-20 08:28:16 UTC")。我只想从字符串中获取年、月、日字段。我试过以下方法,但不确定问题出在哪里。有人能纠正我吗。我已经从StackOverflow那里找到了一些答案,但没有任何帮助。你知道吗

from datetime import datetime
date_posted=str("2014-05-12 00:00:00")
date_posted_zone=str("2015-01-20 08:28:16 UTC")

def convert_timestamp(date_timestamp=None):
    if '%Z' in date_timestamp:
        d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
    else:
        d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
    return d.strftime("%Y-%m-%d")

print convert_timestamp(date_posted_zone)

Tags: 数据方法字符串jsonzoneconvertdatetimedate
2条回答

我试着用下面的代码来搜索str中的时区及其工作状态。你知道吗

from datetime import datetime
date_posted=str("2014-05-12 00:00:00")
date_posted_zone=str("2015-01-20 08:28:16 UTC")
zone=date_posted_zone.split(" ")
print(zone[2])
def convert_timestamp(date_timestamp=None):
    if zone[2] in date_timestamp:
        d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
    else:
        d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
    return d.strftime("%Y-%m-%d")

print convert_timestamp(date_posted_zone)

您正在检查文本字符串%Z是否在时间戳值中;只有strptime(和strftime)可以实际使用格式字符。你知道吗

你能做的就是简单地试着解析字符串,就像它有一个时区,如果失败了,试着不带时区地解析它。你知道吗

def convert_timestamp(date_timestamp=None):
    try:
        d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
    except ValueError:
        d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
    return d.strftime("%Y-%m-%d")

当然,如前所述,您根本不需要解析字符串;只需在空白处拆分它并返回第一个组件。(现有代码已假定年/月/日期匹配。)

def convert_timestamp(date_timestamp):
    return date_timestamp.split()[0]

相关问题 更多 >