Py学习  »  Python

Python日期时间转换器

SeaDude • 3 年前 • 1207 次点击  

我正试图编写一个Python函数,将传入的时间戳标准化为 yyyy-mm-ddThh:mm+/-tz offset .

例子:

def format_ts(ts):
                
    beg_format = [
        '%H:%M%a, %b %d, %Y %Z',
        '%a, %d %b %Y %H:%M:%S %z',
    ]

    end_format = '%Y-%m-%dT%H:%M %z'

    try:
        for f in beg_format:
            if datetime.strptime(ts, f):
                ts_fmt = datetime.strptime(ts, f)
                ts_fmt = ts_fmt.strftime(end_format)
                return ts_fmt

    except:
        pass


ts = [
    '08:27Sun, Dec 19, 2021 IST',
    'Sun, 19 Dec 2021 02:28:56 +0000'
]

for t in ts:
    formatted_ts = format_ts(t)
    print(formatted_ts)

问题:

  • IIRC,我不应该依赖失败( pass ),而是应该捕获异常并进行处理
  • 上述函数通过所有格式迭代所有时间戳(慢)
  • 除非我错过了什么, IST 没有人读 %Z
  • 出于某种原因, '%a, %d %b %Y %H:%M:%S %z' 不适用于的格式不正确 ts[1]

问题: 其他人是如何在Python中处理此类问题的?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128979
 
1207 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Chris
Reply   •   1 楼
Chris    3 年前

strTime的字符串表示形式似乎不支持您的时区。您可以使用带有时区的dateutil解析器来解决这个问题。

from dateutil import parser, tz

ts = [
    '08:27Sun, Dec 19, 2021 IST',
    'Sun, 19 Dec 2021 02:28:56 +0000'
]


def format_ts(ts):
    return [parser.parse(t, tzinfos={'IST':tz.gettz('Asia/Calcutta')}) for t in ts]

format_ts(ts)

输出

[datetime.datetime(2021, 12, 19, 8, 27, tzinfo=tzfile('Asia/Calcutta')),
 datetime.datetime(2021, 12, 19, 2, 28, 56, tzinfo=tzutc())]