Home > Net >  converting 3 digit integers in a column to dates?
converting 3 digit integers in a column to dates?

Time:06-21

I have an a column with 3 digit integers as m/dd. eg.-

410
417
505
522

I want to convert them to

2022-04-10
2022-04-17
2022-05-05
2022-05-22

CodePudding user response:

You can use .apply() to format the integers as strings, and then use pd.to_datetime() to turn those strings into dates. Notably, this approach works even if the month is represented by two digits (i.e. October, November, or December):

import pandas as pd

df = pd.DataFrame([410, 417, 505, 522, 1222], columns=["dates"])
df["dates"] = df["dates"].apply(lambda x: "{:02}/{:02}/2022".format(x // 100, x % 100))
df["dates"] = pd.to_datetime(df["dates"], format="%m/%d/%Y")

This outputs:

       dates
0 2022-04-10
1 2022-04-17
2 2022-05-05
3 2022-05-22
4 2022-12-22

CodePudding user response:

That representation doesn't really make sense, since October, November, and December cannot be represented under that scheme. That being said, the code you want is as follows:

import datetime

x = 123
temp = str(x)

myDate = datetime.datetime(2022, int(temp[0]), int(temp[1:3])) # Year, month, date
  • Related