【问题标题】:TypeError when converting datetime object in to UTC将日期时间对象转换为 UTC 时出现 TypeError
【发布时间】:2017-08-22 04:51:20
【问题描述】:

我输入的日期是2017-08-22T11:32:31+10:00

我希望将其转换为 UTC,即 2017-08-22+01:32:31

到目前为止的代码

from datetime import datetime, timedelta
from pytz import timezone
import pytz


fmt = "%Y-%m-%d+%H:%M:%S"
now_time = datetime('2017-08-22T11:32:31+10:00')
zone = 'UTC'

now_time = now_time.timezone(zone)
print now_time.strftime(fmt)

错误

now_time = datetime('2017-08-22T11:32:31+10:00')
TypeError: an integer is required

【问题讨论】:

  • 请在docs阅读有关datetime.datetime对象初始化的更多信息
  • 这不是从字符串构造日期时间对象的方式。你想要datetime.strptime()

标签: python datetime timezone timedelta


【解决方案1】:

您可以在创建datetime 对象时使用dateutil.parser 推断日期时间格式。

import dateutil.parser
your_date = dateutil.parser.parse('2017-08-22T11:32:31+10:00')

接下来,您可以使用.astimezone函数将your_date转换为UTC

utc_date = your_date.astimezone(pytz.utc)
print(utc_date)

输出:

2017-08-22 01:32:31+00:00

【讨论】:

    猜你喜欢
    • 2016-08-27
    • 2012-03-15
    • 1970-01-01
    • 2020-03-07
    • 2014-05-06
    • 1970-01-01
    • 2021-12-31
    • 2012-10-07
    • 1970-01-01
    相关资源
    最近更新 更多