Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number into a special datetime

Date1 :20061201
Date2 :01/12/2006

How could use pandas in Python to convert date1 into date2(day/month/year) format?Thanks!Date1 and Date2 are two column in csv files.

like image 583
andrew Avatar asked Nov 27 '25 22:11

andrew


2 Answers

Data:

In [151]: df
Out[151]:
       Date
0  20061201
1  20170530

Option 1:

In [152]: pd.to_datetime(df.Date, format='%Y%m%d').dt.strftime('%d/%m/%Y')
Out[152]:
0    01/12/2006
1    30/05/2017
Name: Date, dtype: object

Option 2:

In [153]: df.Date.astype(str).str.replace('(\d{4})(\d{2})(\d{2})', r'\3/\2/\1')
Out[153]:
0    01/12/2006
1    30/05/2017
Name: Date, dtype: object
like image 85
MaxU - stop WAR against UA Avatar answered Nov 30 '25 13:11

MaxU - stop WAR against UA


If you're using pandas and want a timestamp object back

pd.to_datetime('20061201')

Timestamp('2006-12-01 00:00:00')

If you want a string back

str(pd.to_datetime('20061201').date())

'2006-12-01'

Assuming you have a dataframe df

df = pd.DataFrame(dict(Date1=['20161201']))

Then you can use the same techniques in vectorized form.

as timestamps

df.assign(Date2=pd.to_datetime(df.Date1))

      Date1       Date2
0  20161201  2016-12-01

as strings

df.assign(Date2=pd.to_datetime(df.Date1).dt.date.astype(str))

      Date1       Date2
0  20161201  2016-12-01
like image 26
piRSquared Avatar answered Nov 30 '25 13:11

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!