【问题标题】:I am having trouble formatting a date using datetime我在使用日期时间格式化日期时遇到问题
【发布时间】:2021-03-10 04:19:06
【问题描述】:

我从 API 中获取了一个日期,我在使用 datetime 格式化后尝试将其传递给我的模板,但我不断收到此错误:

时间数据2021-03-09T05:00:00.000Z与格式不匹配%Y-%m-%d, %I:%M:%S;%f

我知道我必须先 strftime 然后 strptime 但我无法克服那个错误。

我想将它分成两个变量,一个用于日期,一个用于将在用户时区显示的时间。

    date = game['schedule']['date']
    game_date = datetime.strptime(date, '%Y-%m-%d, %I:%M:%S;%f')

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    你的时间格式有点不对:

    game_date = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ')
    

    或者(如果你从日期字符串中删除最后一个Z字符)你也可以使用datetime.fromisoformat:

    game_date = datetime.fromisoformat(date[:-1])
    

    然后你可以这样提取日期和时间:

    date = game_date.date()
    time = game_date.time()
    time_with_timezone = game_date.timetz()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      相关资源
      最近更新 更多