convert numbers column into a date for timeseries analysis

107 views Asked by At

how do I convert a series of numbers(0 to 881) into a date. example :

n= [0,1,2,3,....881]
output = 01-01-2015 to somewhat 25-05-2017 . 

It doesn't matter what's starting date is . i just want to convert the number column into a date .

2

There are 2 answers

0
Suryaveer Singh On

You can use timedelta to covert numbers to date with respect to the initial date.

CODE

from datetime import datetime, timedelta
start_date = '01-01-2015'
date_format =  "%m-%d-%Y"
initial_date = datetime.strptime(start_date,date_format)

#generate list 
n = list(range(0,882))

#convert int to dates usign time delta with days
date_list = [(initial_ordinal + timedelta(days=i)).strftime(date_format) for i in n]

OUTPUT

date_list
['01-01-2015',
 '01-02-2015',
 '01-03-2015',
 '01-04-2015',
 '01-05-2015',
 '01-06-2015',
 '01-07-2015',
 '01-08-2015',
  ......
 '05-31-2017'
]
0
jsmart On

Here is one way:

xs = [0, 1, 2, 3, 4, 5]

pd.to_datetime(xs, unit='D', origin='2019-12-29')

# result
DatetimeIndex(['2019-12-29', '2019-12-30', '2019-12-31', '2020-01-01',
               '2020-01-02', '2020-01-03'],
              dtype='datetime64[ns]', freq=None)

Result is a DatetimeIndex, which you can assign to a column in a data frame.