Adding 0 in front of date

Viewed 89

New to programming: I have a CSV file in which date is given in format DDMMYYYY, while reading the file in python its type is taken as int. So a date say 01022020 is being taken as 1022020. I need to add the 0 in front of all these dates wherein dates' len is less than 8.

Index           Date              Value
0             10042020            10.5
1             03052020            14.2
2             09052020            16.3
3             13052020            17.5

I converted the column to str using df.Date.map(str) but can't understand how to proceed.

I tried:

if len(df.Date[i])==7:
        df.Date[i]= df.Date.str["0"]+df.Date.str[i]

Its not working. I have two queries regarding this:

  1. want to understand why is this wrong logically and what's the best solution.

  2. While reading the data from CSV file, can a column having integers only be converted to string directly?

Please help.

3 Answers
 print(df)#input

     Index      Date  Value
0      0  10042020   10.5
1      1   3052020   14.2
2      2   9052020   16.3
3      3  13052020   17.5

convert date column to string using .astype(str) and pad any strings whose len is less than 8 using .str.pad() method

 df['Date']=df['Date'].astype(str).str.pad(width=8, side='left', fillchar='0')

    Index      Date  Value
0      0  10042020   10.5
1      1  03052020   14.2
2      2  09052020   16.3
3      3  13052020   17.5

if needed in datetime object, then;

df['Date']=pd.to_datetime(df['Date'],format='%d%m%Y')

Chained together;

df['Date']=pd.to_datetime(df['Date'].astype(str).str.pad(width=8, side='left', fillchar='0'),format='%d%m%Y')

Use, .str.zfill:

s = pd.Series([1122020, 2032020, 12312020])
s

Input series:

0     1122020
1     2032020
2    12312020
dtype: int64

Use cast to string then use zfill:

s.astype(str).str.zfill(8)

Output:

0    01122020
1    02032020
2    12312020
dtype: object

Then you can use pd.to_datetime with format:

pd.to_datetime(s.astype(str).str.zfill(8), format='%m%d%Y')

Output:

0   2020-01-12
1   2020-02-03
2   2020-12-31
dtype: datetime64[ns]

The simplest solution I've seen for converting an int to a string that's left-padded with zeroes is to use the zfill command e.g. str(df.Date[i]).zfill(8)

Assuming you're using pandas for your csv load, you can specify the dtype on load: df = pd.read_csv('test.csv', dtype={'Date': 'string'})

Related