python – Parse date string and change format

python – Parse date string and change format

datetime module could help you with that:

datetime.datetime.strptime(date_string, format1).strftime(format2)

For the specific example you could do

>>> import datetime
>>> datetime.datetime.strptime(Mon Feb 15 2010, %a %b %d %Y).strftime(%d/%m/%Y)
15/02/2010
>>>

You can install the dateutil library. Its parse function can figure out what format a string is in without having to specify the format like you do with datetime.strptime.

from dateutil.parser import parse
dt = parse(Mon Feb 15 2010)
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.strftime(%d/%m/%Y))
# 15/02/2010

python – Parse date string and change format

convert string to datetime object

from datetime import datetime
s = 2016-03-26T09:25:55.000Z
f = %Y-%m-%dT%H:%M:%S.%fZ
out = datetime.strptime(s, f)
print(out)
output:
2016-03-26 09:25:55

Leave a Reply

Your email address will not be published. Required fields are marked *