I have a problem in Python 3.9 64x bit. In a program I am writing, I need to be able to convert any inputted date into the format %d%m%y. For example, if the user entered 12 December 2021, the program will convert it to 121221, and if the user enters 2021 12 December, it will still convert it to 121221.
Asked
Active
Viewed 600 times
0
-
If ambiguity is not expected, split the string and guess each substring. A day has len() < 3, a month is in the set of months the least is a year. If ambiguity is possible the task is impossible. – Askold Ilvento Nov 15 '20 at 14:04
-
1It seems ironic that you convert the dates to a totally ambiguous format. If the user imputted "121221", how do you decide what year/century was intended? – ekhumoro Nov 15 '20 at 14:13
-
I am trying to scrape skyscanner, and I need the date to be in this format to work – The Pilot Dude Nov 20 '20 at 18:34
2 Answers
1
You could use pandas
to_datetime
and then strftime
.
from pandas import to_datetime
to_datetime('12 December 2021').strftime('%d%m%y') ## returns 121221
to_datetime('2021 12 December').strftime('%d%m%y') ## returns 121221
pandas
tries to infer the format when parsing the string.
Note, without specifying the datetime format for the string entered by the user there is of course ambiguity. E.g. what is meant by a the string '11/12/2021'
. It could be '11 December 2021'
or '12 November 2021'
.
this of course is error prone if the user enters

Stefan
- 1,697
- 15
- 31
0
>>> from_date="12 December 2021"
>>> import time
>>> conv=time.strptime(from_date,"%d %B %Y")
>>> time.strftime("%d/%m/%y",conv)
'121221'
>>> from_date="2021 12 December"
>>> import time
>>> conv=time.strptime(from_date,"%Y %d %B")
>>> time.strftime("%d%m%y",conv)
'121221'

Ehtisham Ahmed
- 387
- 3
- 15