Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I'm preprocessing data and one column represents dates such as '6/1/51'

I'm trying to convert the string to a date object and so far what I have is:

    date = row[2].strip()

    format = "%m/%d/%y"

    datetime_object = datetime.strptime(date, format)

    date_object = datetime_object.date()

    print(date_object)

    print(type(date_object))

enter image description here

The problem I'm facing is changing 2051 to 1951.

I tried writing

    format = "%m/%d/19%y"

But it gives me a ValueError.

    ValueError: time data '6/1/51' does not match format '%m/%d/19%y'

I couldn't easily find the answer online so I'm asking here. Can anyone please help me with this?

Thanks.

1 Answer

0 votes
by (41.4k points)

Parsing the date without the century using '%m/%d/%y'

After that, put the conditionals in order to format it to 1900.

year_1900 = datetime_object.year - 100

datetime_object = datetime_object.replace(year=year_1900)

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 11, 2019 in BI by Vaibhav Ameta (17.6k points)
0 votes
1 answer
asked Feb 27, 2020 in BI by Vaibhav Ameta (17.6k points)

Browse Categories

...