【问题标题】:How to get date in correct format for YouTube upload?如何以正确的格式获取 YouTube 上传的日期?
【发布时间】:2018-05-12 08:47:21
【问题描述】:

我正在 OSX 上运行一个 python 脚本来将视频文件 (single_file) 上传到 YouTube:

# define recording date as date of file modification
# https://developers.google.com/youtube/v3/docs/videos#resource
recordingDate = datetime.fromtimestamp(os.path.getctime(single_file)).isoformat("T")+"Z"

# define video title as file name
filename, file_extension = os.path.splitext(os.path.basename(single_file)) 

try:
  initialize_upload(youtube, args, single_file, title, recordingDate)
except HttpError, e:
  print "  An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

在某些情况下它运行良好,但在其他情况下,Google 会返回以下错误 -

Invalid value for: Invalid format: \"2017-09-22T22:50:55Z\" is malformed at \"Z\"

我应该如何修复它以从文件中获取正确的日期? YouTube 需要 ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) 格式的值。

【问题讨论】:

  • 有效的日期是什么时候?
  • 看起来他们也可能需要 1/10 秒。你有没有试过 +".0Z" 而不是 +"Z"?

标签: python datetime youtube-api datetime-format


【解决方案1】:

您在问题中分享的链接清楚地说明了格式

该值以 ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) 格式指定。

所以你的问题是当微秒信息不可用时,isoformat 将没有微秒。下面的代码显示了区别

>>> current_date = datetime.now()
>>> current_date.isoformat()
'2018-05-20T10:18:26.785085'
>>> current_date.replace(microsecond=0).isoformat()
'2018-05-20T10:18:26'

所以对于它工作的文件,microsecond 将是非零。所以解决方案很简单

recordingDate = datetime.fromtimestamp(os.path.getctime(single_file)).replace(microsecond=0).isoformat("T")+".0Z"

这将确保微秒始终被截断并稍后设置为.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2020-05-18
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2013-08-14
    相关资源
    最近更新 更多