1

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?

Johnn Kaita
  • 432
  • 1
  • 3
  • 13
  • 2
    Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – Russ J Nov 08 '20 at 05:45

2 Answers2

0

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

Fading Origami
  • 203
  • 1
  • 8
0

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.

Philip Ciunkiewicz
  • 2,652
  • 3
  • 12
  • 24