-2

If I have a string that contain a date, like '29/01/21', how can I convert its format to a 4 year digit instead of 2 digits?

'29/01/21'

to

'29/01/2021'
  • 2
    There's absolutely no reason to reintroduce the Y2K bug. Don't store such dates for ANY reason. Especially not in 2021, one year after Lloyds and RBS banking systems crashed when their hacky Y2K "fixes" started treating `20` as 1920 – Panagiotis Kanavos Feb 04 '21 at 19:27
  • Thats the first time that I heard about this bug. But I'm trying to store a year with 4 digit not 2. There is no problems on it, right? – Danilo Matrangolo Marano Feb 04 '21 at 19:33
  • This is only [the most famous, most expensive bug in the history of computing](https://en.wikipedia.org/wiki/Year_2000_problem). There are even a dozen LOT of movies about this, including [Entrapment with Sean Connery](https://en.wikipedia.org/wiki/Entrapment_(film)). As for storing dates, dates are NOT strings. `datetime` is a binary value, both in Python and all databases (except SQLite). Again, never, ever use or allow 2-digit dates. Besides, why assume 21 is 2021? [Captain Tom](https://www.bbc.com/news/uk-england-beds-bucks-herts-52324058) was born in 1920. You *can't* assume `21` is 2021 – Panagiotis Kanavos Feb 04 '21 at 19:37
  • 1
    To put it it in perspective, you really *REALLY* wouldn't want to mess up vaccinations because of a Y2K bug. There are a *lot* of people getting vaccinated right now whose birth dates would change by 100 years if you only stored two digits – Panagiotis Kanavos Feb 04 '21 at 19:41
  • Unfortunately, some of us get data coming in like this because they come from legacy systems that we don't control. But someone not having heard of the Y2K but makes me feel ancient. – David Grenier Jan 11 '22 at 17:16
  • I'm from Brazil and not everybody knows this bug, it is not so popular like it is in the USA or in Europe, I suppose. I'm really sure that in 2100 this bug will happen again. – Danilo Matrangolo Marano Jan 12 '22 at 02:20

2 Answers2

3

Pythons datetime library might be helpful.

Please refer below code.

from datetime import datetime

datetime.datetime.strptime('29/01/21', '%d/%m/%y').strftime("%M/%d/%Y")
Ruli
  • 2,592
  • 12
  • 30
  • 40
shajahan
  • 102
  • 3
1

This is one solution:

mystring = '29/01/21'
mystring = mystring[:6]+'20'+mystring[-2:]
print(mystring)

Output:

'29/01/2021'
ph140
  • 478
  • 3
  • 10