【问题标题】:Converting string (with timezone) to datetime in python在python中将字符串(带时区)转换为日期时间
【发布时间】:2020-02-27 10:26:13
【问题描述】:

我的目标是转化

stringtime = '2020-02-30 10:27:00+01:00'

这样我可以比较一下

nowtime = datetime.datetime.utcnow()

使用

if nowtime > stringtime:
    print(1)

我试过strptime:

datetime.datetime.strptime(stringtime, '%Y-%m-%d %H:%M:%S')

但在 strptime 文档中找不到时区的格式规范。

我也试过

pandas.Timestamp(stringtime)

但我得到ValueError: could not convert string to Timestamp。

如何做到这一点?

【问题讨论】:

标签: python datetime datetime-conversion


【解决方案1】:
datetime.datetime.strptime(stringtime, '%Y-%m-%d %H:%M:%S%z')

将为您提供预期的结果%z 是格式(仅限 Python3),但是您的原始日期无效,因为 2 月没有 30 天 :)

【讨论】:

  • 通过向两个变量添加 .replace(tzinfo=tzutc()) 使其工作
【解决方案2】:

首先:您的stringtime 是错误的,不存在2 月30 日。 ;)

你可以通过dateutil实现你想要的:

import dateutil.parser
stringtime = '2020-03-30 10:27:00+01:00'
dateutil.parser.isoparse(stringtime)
# datetime.datetime(2020, 3, 30, 10, 27, tzinfo=tzoffset(None, 3600))

【讨论】:

  • 这将引发 TypeError: can't compare offset-naive and offset-aware datetimes :(
  • 通过向两个变量添加 .replace(tzinfo=tzutc()) 使其工作
猜你喜欢
  • 2017-09-08
  • 2021-03-09
  • 1970-01-01
  • 2021-10-17
  • 2017-07-29
  • 1970-01-01
  • 2015-01-22
  • 1970-01-01
  • 2015-03-24
相关资源
最近更新 更多