python - 如何获取正确格式的日期以供 YouTube 上传?

标签 python datetime youtube-api datetime-format

我正在 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) 格式的值。

最佳答案

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

The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.

所以你的问题是当微秒信息不可用时,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'

因此,对于它工作的文件,微秒将是非零的。所以解决办法很简单

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

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

关于python - 如何获取正确格式的日期以供 YouTube 上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304415/

相关文章:

javascript - Youtube API : Starting video doesn't work

python - 当我在加载模型后加载 cuda() 之前应用 torch.manual_seed 时,结果不同

python - 导入错误: cannot import name Ward

mysql - 如何更新 MySQL 中的两个(或更多)可靠列

javascript - 使用 Moment.js 检测北半球或南半球

android - 服务com.google.android.youtube.api.service.YouTubeService泄漏了IntentReceiver uds @ 5fa5135

python - mongoengine max_distance 查询的数据库错误

python - 条件语句在我的 Python 代码中不起作用

c# - DateTime 是否在 C# 中保持自身更新?

python - Youtube API 请求凭据