Converting Django printed date and time to another date and time format

My web application works with datetime (s) as the timestamps, which, according to reports on the Django error should be in the following format: YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]

.

I show these time intervals several times in a web application, where they are displayed in the following format: 12. June 2017 10:17

.

The user can now select and submit the displayed time zones, which are then processed by the server. Then the server will fail because the format is not correct.

How do I convert the format printed by Django in the web application ( 12. Juni 2017 10:17

) to the format Django needs for further processing ( YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]

)?

edit: We are currently trying to create a datetime object from the received data and then convert it to the required format.

parsed_timestamp = datetime.datetime.strptime(request.POST['timestamp'], "%y/%m/%d %B")

      

This results in the following error:

time data '12. June 2017 10:17' does not match format '%y/%m/%d %B'

      

+3


source to share


3 answers


Your problem is that it "%y/%m/%d %B"

doesn't match the pattern'12. June 2017 10:17'

For parsing the date correctly, you can try this:

>>> 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 determine what percentage values ​​to use from this helpful table in the documentation here

+1


source


Yes, it expects a 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 a valid accepted format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ])

+1


source


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

day

... month in locale full name

year with century

hour

:minute

To convert this to a datetime object using strptime use:

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

      

to convert back use the equivalent strftime

with your format string.

+1


source







All Articles