vnan
vnan

Reputation: 3

Convert array of numbers into dates

I would like to convert an array of numbers [YYYYMMDD,YYYYMMDD,...] into dates, so I could operate on them doing subtactions. My final goal is to obtain an array with the elapsed time in days starting from the first value x_0. To do this, I must run an iteration which replaces each x_n with (x_n - x_0), but I have to convert the numbers in a proper way, so I can do the subtraction and obtain coherent values. I wonder if there is a simple way to convert numpy arrays in a way useful to my purpose.

Upvotes: 0

Views: 1048

Answers (2)

frangaren
frangaren

Reputation: 498

Since they are numbers you can use integer arithmetics to extract the year, the month and the day. And, using this, you can construct datetime.date. Below there is a function that can convert one of your numbers to a date object.

import datetime

def number_to_date(number):
  year = number // 10000
  month = number // 100 - year * 100
  day = number - month * 100 - year * 10000
  return datetime.date(year, month, day)

You can use it inside a for loop or inside a map to convert all of them and then do with them whatever you want. For example:

numbers = np.array([20200829, 20200910, 20201015])
dates = list(map(number_to_date, numbers))
base_date = dates[0]
deltas = np.array(list(map(lambda date: (date - base_date).days, dates)))

print(deltas)

You can drop the np.arrays if you want. They are just there because you said you were using NumPy.

Upvotes: 1

jupiterbjy
jupiterbjy

Reputation: 3503

This will do:

from datetime import datetime

date_format = "%Y%m%d"

generated = datetime.now().strftime(date_format)
print(type(generated))
print(generated)

back_to_datetime = datetime.strptime(generated, date_format)
print(type(back_to_datetime))
print(back_to_datetime)

Output:

<class 'str'>
20200829
<class 'datetime.datetime'>
2020-08-29 00:00:00

Upvotes: 0

Related Questions