I have a date that is generated from the user side. However this date is in string format Here is an example below:
period = '12-4-2020'
how can I convert it to datetime format?
I have a date that is generated from the user side. However this date is in string format Here is an example below:
period = '12-4-2020'
how can I convert it to datetime format?
try this
from datetime import datetime
period = '12-4-2020'
result = datetime.strptime(period, '%d-%m-%Y')
print(result)
The second argument, '%d-%m-%Y' in the strptime function is called the format. What it means is, it is the date format you want to convert from.
In your case,
'12' -> '%d'
'4' -> '%m'
'2020' -> '%y'
For more formats, you can see here
You can use the datetime.datetime.strptime
method:
period = '12-4-2020'
datetime.datetime.strptime(period, '%m-%d-%Y')
or (the order of day month year is ambiguous based on that date string)
datetime.datetime.strptime(period, '%d-%m-%Y')
The first argument is your date string, and the second argument is the string format.