简体   繁体   English

从Excel文件中读取日期并获取今天日期的增量

[英]Read date from Excel file and get a delta with today's date

I have an excel file with some dates in it. 我有一个excel文件,里面有一些日期。 They're formatted with dd-mm-yyyy . 它们的格式为dd-mm-yyyy I would like to take each date in that column and get a delta of it with today's date. 我想在该列中记录每个日期,并在今天的日期获得它的增量。

For example, if the Excel file has a date as so: 20-6-2019, it will subtract today's date (16/6/2019) and return 4. 例如,如果Excel文件的日期如下:20-6-2019,它将减去今天的日期(16/6/2019)并返回4。

I've been trying to approach this with pandas and with xlrd, but each time I'm getting overwhelmed and just couldn't understand what I'm doing. 我一直试图用pandas和xlrd来解决这个问题,但每次我都不知所措,只是无法理解我在做什么。

This was my approach: 这是我的方法:

import pandas as pd
import datetime

file_name = pd.read_excel (r'C:\Users\Daniel Beilin\VSCodeProjects\ExcelReminder\test.xlsx')
df = pd.DataFrame(file_name, columns= ['Date'])
df['Date'] = pd.to_datetime(df.Date)

frmtedDate = df['Date']
today = pd.datetime.now().date()

delta = frmtedDate - today
print(delta)

You can use pd.Timestamp.today and then extract the amount of days from the timedelta which it returns with dt.days : 您可以使用pd.Timestamp.today ,然后从dt.days返回的timedelta中提取天dt.days

# Example dataframe
df = pd.DataFrame({'Date':['20-6-2019', '21-6-2019', '25-6-2019']})
df['Date'] = pd.to_datetime(df['Date'])

        Date
0 2019-06-20
1 2019-06-21
2 2019-06-25

(df['Date'] - pd.Timestamp.today()).dt.days

0    3
1    4
2    8
Name: Date, dtype: int64

Note in this case 3 days for 20-6-2019 is correct, since there are 3 full days between date now and the 20th of june. 请注意,在这种情况下, 20-6-2019 3天是正确的,因为从现在到6月20日之间有3天完整。

You can set a format option in you pd.to_datetime() function. 您可以在pd.to_datetime()函数中设置格式选项。 In your situation this should work out: 在你的情况下,这应该成功:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM