SaAtomic
SaAtomic

Reputation: 749

Convert datetime printed by Django, to a different datetime format

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

I display these timestimes on multiple occasions on the web application, where they're displayed in the following format: 12. June 2017 10:17.

Now, the user is able to choose and submit the displayed timezones, which are then processed by the server. The server then error's because the format isn't correct.

How do I convert the format printed by Django on the web app (12. Juni 2017 10:17) to the format, required by Django for further processing (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ])?

edit: Currently trying to create a datetime object of the received data, then convert it to the required format.

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

Which results in the following error:

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

Upvotes: 3

Views: 4987

Answers (3)

Dschoni
Dschoni

Reputation: 3862

(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.

Upvotes: 1

void
void

Reputation: 2642

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])

Upvotes: 1

Jack Evans
Jack Evans

Reputation: 1717

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

Upvotes: 1

Related Questions