简体   繁体   中英

Convert a particular timestamp with Python 2.7.x

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM