Home > Enterprise >  Extraction of day, month and year from the date 4.5.6
Extraction of day, month and year from the date 4.5.6

Time:10-16

Which function can I use to extract day, month and year from dates written in this manner 4.5.6 where 4 is the day, 5 is the month and 6 is the year (presumably 2006). I have already tried using dateparser.parse but it is not working.

CodePudding user response:

day, month, year = map(int, '4.5.6'.split('.'))

And then add 2000 as necessary to the year.

You can then construct a datetime object with

from datetime import datetime
dt = datetime(year, month, day)

While it would be logical to use datetime.strptime, the one-digit year messes things up, and the above will just work fine.

CodePudding user response:

Here is how you can use the datetime.datetime.strptime() method:

import datetime

s = "4.5.6"
i = s.rindex('.')   1
s = s[:i]   s[i:].rjust(2, '0') # Add padding to year
dt = datetime.datetime.strptime(s, "%d.%m.%y")
print(dt)

Output:

2006-05-04 00:00:00

With the resulting datetime.datetime object, you can access plenty of information about the date, for example you can get the year by printing dt.year (outputs 2006).

  • Related