【问题标题】:Aware iso 8061 to datetime Python知道 iso 8061 到 datetime Python
【发布时间】:2017-11-25 12:05:50
【问题描述】:

我输入以下字符串:

input = "20170620015620.222+0000"

要将其转换为datetime,我可以使用如下内容:

utc_format_regex = re.compile('(?P<year>\d{4})'
                                      '(?P<month>\d{2})'
                                      '(?P<day>\d{2})'
                                      '(?P<hour>\d{2})'
                                      '(?P<minute>\d{2})'
                                      '(?P<second>\d{2})'
                                      '\.'
                                      '(?P<milisecond>\d{3})'
                                      '(?P<tz>\+\d{4})')
year, month, day, hour, minute, second, milisecond, tz = utc_format_regex.match(value).groups()

将其解析为 datetime 似乎很容易,除了 param tzinfo (我不知道如何正确使用它)。该代码不会因为这样的错误而工作:

TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'unicode'

datetime(year=int(year), month=int(month), day=int(day), hour=int(hour), minute=int(minute), second=int(second),
                                     microsecond=int(milisecond) * 1000, tzinfo=tz)

【问题讨论】:

  • input 不应用作变量名
  • 不是。我只是在这里输入的。不过好点

标签: python datetime iso


【解决方案1】:

只需使用strptime:

import datetime
parsed = datetime.datetime.strptime(input, '%Y%m%d%H%M%S.%f%z')

【讨论】:

  • 对 python 2 用户的警告:%f 可能受支持,也可能不受支持,具体取决于您的操作系统和解释器。
  • %z 在我的版本(或服务器版本)下不受支持。不能那样做,这是 2.7 Python
  • 你有,为什么 %z 不工作。 stackoverflow.com/questions/20194496/…
  • 运气不好,你可能需要pytz模块。
  • 看来,你可以这样做: 'tz = int(tz[1:])/1000*3600' 'datetime(year=int(year), month=int(month), day =int(day), hour=int(hour), minute=int(minute), second=int(second), microsecond=int(milisecond) * 1000, tzinfo=dateutil.tz.tzoffset(None,tz))'我不知道,虽然负值会发生什么......它应该是负数吗?
猜你喜欢
  • 1970-01-01
  • 2021-05-29
  • 2021-09-08
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多