LA_
LA_

Reputation: 20409

How to get date in correct format for YouTube upload?

I am running a python script on OSX to upload video file (single_file) to 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)

in some cases it works well, but in others Google returns the following error -

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

How should I fix it to get correct date from the file? YouTube expects the value in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.

Upvotes: 2

Views: 1620

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146510

The link you shared in your question clearly states the format

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

So your issue is when then the microsecond info is not available, the isoformat will not have microsecond. Below code shows the difference

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

So for the files which it works the microsecond would be coming is non-zero. So solution is simple

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

This will make sure the microsecond is always truncated and set as .0 later

Upvotes: 5

Related Questions