import csv
f = csv.reader(open('lmt.csv', 'r')) # open input file for reading
Date, Open, Hihh, mLow, Close, Volume = zip(*f) # split it into separate columns
现在我想从 Date
中选择两个日期列并计算它们之间的天数。
遗憾的是,由于它们是从 .csv 文件中检索的,因此它们采用“'\xef\xbb\xbfDate'”格式。
所以当我尝试使用datetime
时模块,它不起作用。
我能想到的一件事是让excel通过=DATEDIF(A2, B2, "d")
进行计算但我希望有一个更优雅的解决方案。
最佳答案
作为my answer的后续发送至您的 previous questions 之一(其中还可以找到数据文件的链接),以下内容可以正常工作。下面的代码将计算 df['Date'][0]
之间的天数('2016 年 2 月 17 日')和 df['Date'][10]
(“2016 年 2 月 2 日”)。您收到的输出是:
The difference are 15 days.
这是带有一些内联注释的代码:
import pandas as pd
from datetime import datetime
df = pd.read_csv('lmt.csv')
# get rid of the format issue
df.rename(columns={df.columns[0]: 'Date' }, inplace=True)
# define your format in the Date column
date_format = '%d-%b-%y'
# select the first date
date1 = datetime.strptime(df['Date'][0], date_format)
# select the second date
date2 = datetime.strptime(df['Date'][10], date_format)
# calculate the difference between the dates
diffDates = date1 - date2
# print results in days
print 'The difference are ' + str(diffDates.days) + ' days.'
如果您想要的输出不是以天为单位而是以小时为单位,您可以检查 this post .
编辑
对于您需要的新文件:
date_format = '%Y-%m-%d'
然后就可以正常工作了。检查this link 了解不同格式的详细说明。
关于python - 如何计算两个给定日期之间的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528839/