You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OSX下Python脚本上传YouTube:如何生成合规日期格式?

Fixing Invalid ISO 8601 Date Format for YouTube API Uploads on macOS

Let's break down this issue you're facing with the YouTube API. The error message makes it clear: your current date string is missing the fractional seconds component that YouTube requires in the ISO 8601 format (YYYY-MM-DDThh:mm:ss.sZ). When your file's timestamp doesn't include sub-second precision, the isoformat("T") method skips that decimal part entirely, resulting in 2017-09-22T22:50:55Z — which gets rejected because the API expects something like 2017-09-22T22:50:55.000Z (even if the milliseconds are zero).

Here's how to modify your code to consistently generate a valid date string:

import os
from datetime import datetime

# Get the file's creation time (returns a float with microseconds on macOS)
file_creation_time = os.path.getctime(single_file)
# Convert to a datetime object that preserves sub-second precision
recording_dt = datetime.fromtimestamp(file_creation_time)
# Format to ISO 8601 with milliseconds, then append the 'Z' UTC indicator
recordingDate = recording_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"

What this does:

  • Preserve sub-second precision: os.path.getctime() on macOS returns a floating-point number that includes microseconds, so converting it directly to a datetime keeps that detail.
  • Format with milliseconds: The strftime pattern %f adds microseconds, and we slice the last 3 characters ([:-3]) to truncate it to milliseconds — which matches the .s requirement in YouTube's format.
  • Ensure consistency: Even if the file's timestamp has no sub-second data (e.g., an integer timestamp), this code will still generate .000 for the milliseconds, so the final string will always meet the API's formatting rules.

If you're using Python 3.6 or later, you can also use a more concise approach with isoformat's timespec parameter (though note your original code uses Python 2 syntax, so this might not apply):

recordingDate = recording_dt.isoformat(timespec='milliseconds').replace('+00:00', 'Z')

Either way, this should resolve the "Invalid format" error from the YouTube API, since your date string will now always include the required fractional seconds part before the Z.

内容的提问来源于stack exchange,提问作者LA_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:30:57