PSU2017 PSU2017 - 9 months ago 49
Python Question

Converting from <day> <time> to DateTime in python and Django, and back

Im trying to use strptime to convert a day and time into a DateTime field. That is, convert input like "Friday 3:00 PM" to a datetime field. The event this is for takes place over three consecutive days, so I know that Friday will be a specific day in February, and so on.

My question, is how do I go about doing this? How do I convert, for example, Friday 3:00 PM into 2017-02-24 15:00:00?

What I have right now in my Django project, in is:

new_request.start = time.strptime(form.cleaned_data['start'], '%A %I:%M %p')

Then, I have to print out "Friday 3:00 PM" from the datetime field later, using strftime, which I would assume is the reverse of the above?


Answer Source

You can adapt the example below to achieve what you want exactly:

import time

time.strftime("%Y-%d-%m %H:%M:%S", time.strptime('Friday 3 February 2017 3:00PM', '%A %d %B %Y %I:%M%p'))
# Output: '2017-03-02 15:00:00'

If year and month are fixed to 2017 and February like you mentioned then "Friday 3:00 PM" can be converted as follows:

time.strftime("2017-%d-2 %H:%M:%S", time.strptime('Friday 3 3:00PM', '%A %d %I:%M%p'))
# Output: '2017-03-2 15:00:00'

If you want to get datetime object use the following:

from datetime import datetime

datetime.strptime('Friday 3 February 2017 3:00PM', '%A %d %B %Y %I:%M%p')
# Output: datetime.datetime(2017, 2, 3, 15, 0)