6

The current value that is returned from a GitHub API request looks like this:

2013-09-12T22:42:02Z

How do I parse this value and make it look nicer?

IQAndreas
  • 7,014
  • 4
  • 36
  • 63
  • @Blender I saw that one, but the problem is the recommended code (in the second answer) throws a _ValueError: unconverted data remains: Z_. I posted the proper answer in case anyone else attempts the same thing as I. – IQAndreas Sep 13 '13 at 21:50
  • Not the accepted answer. The second answer will, as it doesn't actually parse the date format properly. – Blender Sep 13 '13 at 21:52
  • @Blender I skipped the accepted answer since it's easier not to have to install modules, but rather use the ones at hand. I preferred just adjusting the `strptime` formatting to fit the GitHub API. – IQAndreas Sep 13 '13 at 21:53
  • Plus the name of this question/answer helps Googlers find a solution if they don't know the name of the date/time standard specifically used by the API. – IQAndreas Sep 13 '13 at 21:57
  • Right, but the returned format is ISO 8601. Parsing it with `datetime.strptime` only handles one specific case of ISO 8601. – Blender Sep 13 '13 at 22:00
  • Just a head's up: [github3.py](https://github.com/sigmavirus24/github3.py) will parse these into datetime objects for you. – Ian Stapleton Cordasco Sep 14 '13 at 01:59

1 Answers1

12

The date format returned from the GitHub API is in the ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ

To convert that string into a Python date object, use the module datetime:

import datetime
date = datetime.datetime.strptime(<date_string>, "%Y-%m-%dT%H:%M:%SZ")

You can then parse this string to the format of your choosing using date.strftime():

# Result: Thursday Sep 12, 2013 at 22:42 GMT
date.strftime('%A %b %d, %Y at %H:%M GMT')

Or if you want it to be more "automatic", the directive %c will automatically choose a date/time string based on your system's locale and language settings.

# On my system, I get the following output:
#  Thu Sep 12 22:42:02 2013
date.strftime('%c')

If you want to customize it, a full list of directives can be found here: http://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

IQAndreas
  • 7,014
  • 4
  • 36
  • 63