[Django]-Convert datetime printed by Django, to a different datetime format

1๐Ÿ‘

โœ…

Your issue is that "%y/%m/%d %B" doesnโ€™t match the pattern '12. June 2017 10:17'

You can try using the following to parse the date correctly:

>>> from dateutil.parser import parse

>>> parse('12. June 2017 10:17')
datetime.datetime(2017, 6, 12, 10, 17)

Or with:

>>> from datetime import datetime

>>> datetime.strptime('12. June 2017 10:17', '%d. %B %Y %I:%M')
datetime.datetime(2017, 6, 12, 10, 17)

You can work out what percentage values to use from this useful table in the documentation here

๐Ÿ‘คJack Evans

1๐Ÿ‘

Yes it expects the format YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] so the Valid values are:

2017-09-04 06:00
2017-09-04 06:00:00
2017-09-04 06:00:00.000000

# w/ optional TZ as timezone. 
2017-09-04 06:00Z # utc
2017-09-04 06:00:00+0800
2017-09-04 06:00:00.000000-08:00

This should do the trick:

import datetime
d = datetime.datetime.strptime('12. June 2017 10:17', '%d. %B %Y %H:%M')
print(d) # or print(str(d)) if you want it as a string 

output:

2017-06-12 10:17:00

which is in the valid accepted format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ])

๐Ÿ‘คvoid

1๐Ÿ‘

(12. Juni 2017 10:17) is in Pseudocode:

day. month in locale full name year with century hour:minute

To convert this into a datetime object with strptime use:

datetime.datetime.strptime(your_input, '%d. %B %Y %H:%M')

to convert back, use the equivalent strftime, with your format string.

๐Ÿ‘คDschoni

Leave a comment