0

I have a timestamp like:

2014-01-01T05:00:00.000Z

How do I convert this so that I can easily get the month like "January"? And in general convert it to a nice format like:

January 1st, 2014

user1087973
  • 800
  • 3
  • 12
  • 29
  • 1
    Possible duplicate of [How to parse an ISO 8601-formatted date in Python?](http://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python) – jermenkoo Nov 12 '15 at 17:44
  • So here's a similar question. I think it will help you. http://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date-in-python – Mitel Razvan Ardelean Nov 12 '15 at 17:50

2 Answers2

3

You can use datetime module. datetime.datetime expects a time string and its formatting and returns a datetime.datetime object, on which you can call strftime() to format it according to your needs.

>>> import datetime
>>> my_date = datetime.datetime.strptime("2014-01-01T05:00:00.000Z", "%Y-%m-%dT%H:%M:%S.%fZ")
>>> my_date.strftime('%d.%m.%Y')
01.01.2014
>>> date.strftime('%H:%M:%S %d.%m.%Y')
'05:00:00 01.01.2014'

There is also a python-dateutils module, which can do the same.

jermenkoo
  • 643
  • 5
  • 20
  • It doesn't produce `January 1st, 2014`. `.strftime('%B %-d, %Y')` produces `'January 1, 2015'` (note: `1`, not `1st`). – jfs Nov 12 '15 at 21:03
1

The strftime() method in datetime modulecan achieve this. It expects a string pattern explaining how you want to format your date.

import datetime

today = datetime.date.today()
print today.strftime('It is %d %b %Y')

The above code prints something like "It is 12 Nov 2015"

You can find more format codes at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

utkbansal
  • 2,787
  • 2
  • 26
  • 47