Answer the question
In order to leave comments, you need to log in
How to convert excel strings to datetime?
There is an Excel file, the structure is as follows:
The first column contains the month and year, then there are values for each day.
How can this be elegantly converted to a datetime DataFrame so that the first column is the date and the second is the data?
Answer the question
In order to leave comments, you need to log in
Pull out data from excel to python lists (whichever is more convenient for you).
It turns out:
data=[
['дата', '1', '2', '3', '4', '5', '6', '7', ...],
['Ноябрь 2019', '11', '22', '33', '44', '55', '66', '77', ...],
['Декабрь 2019', '11', '22', '33', '44', '55', '66', '77', ...],
...
]
import datetime
import locale
def replace_month(dt: str) -> str:
dt = dt.replace('Январь', 'января')
dt = dt.replace('Февраль', 'февраля')
# ...
return dt
locale.setlocale(locale.LC_TIME, "ru_RU.utf8")
head = data[0]
data = data[1:]
result_rows = []
for row in data:
for day, value in zip(head[1:], row[1:]):
dt = replace_month(f'{day} {row[0]}')
try:
dt = datetime.datetime.strptime(dt, '%d %B %Y')
except ValueError:
pass # тут у нас дата не сконвертнулась, например, 30 февраля. Пофиг.
else:
result_rows.append((dt, value))
Hmm, have you tried selecting the first column, pressing Ctrl+1 and setting the cell type as the Custom category and the d-mmm type?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question