[英]How can I extract and further test the list of dates from pandas DatetimeIndex?
There are really two parts to this Question as I am still learning.这个问题实际上有两个部分,因为我仍在学习。
date_list = pd.date_range(2019-09-24, 2019-09-26)
will return an object将返回 object
DatetimeIndex( ['2019-09-24', '2019-09-25'] , dtype='datetime64[ns]', freq='D')
DatetimeIndex( ['2019-09-24', '2019-09-25'] , dtype='datetime64[ns]', freq='D')
However, I just wanted the List in the format it returns shown above.但是,我只想要上面显示的返回格式的列表。 I tried appending .tolist() but it then returns timestamps in a list eg.
我尝试附加.tolist()但它随后返回列表中的时间戳,例如。
Timestamp('2019-09-24 00:00:00', freq='D')
时间戳('2019-09-24 00:00:00', freq='D')
I then used .date which seems to work然后我使用了 .date这似乎有效
print(date_list[0])
2019-09-24
2019-09-24
Is this the best method to use?这是最好的使用方法吗?
Then I came to testing it, I understand this test maybe unnecessary but for the purpose of learning:然后我来测试它,我理解这个测试可能没有必要但出于学习的目的:
def datetimeindex(dates):
start = dates['from_date']
end = dates['to_date']
date_list = pd.date_range(start, end).date
print(date_list[0])
return date_list[0]
def test_datetimeindex(self):
dates = {"from_date": "2019-09-24",
"to_date": "2019-09-27"}
actual = datetimeindex(dates)
expected = "2019-09-24"
self.assertEqual(expected, actual)
I get this error:我收到此错误:
AssertionError: '2019-09-24'.= datetime,date(2019, 9, 24)
AssertionError: '2019-09-24'.= datetime,date(2019, 9, 24)
Why is the print different to the return?为什么打印和退货不一样? If I pass this to another method, what will it actually pass, 2019-09-24 or datetime.date(2019, 9, 24)?
如果我将它传递给另一个方法,它实际上会传递什么,2019-09-24 或 datetime.date(2019, 9, 24)?
I can not assert against datetime.date(2019, 9, 24) as it is not a string, so not sure what to do?我不能断言datetime.date(2019, 9, 24)因为它不是字符串,所以不知道该怎么做?
Thanks谢谢
EDIT: This returned what I wanted.编辑:这返回了我想要的。 which reminded me that print() is always to string, so makes sense.
这提醒我 print() 总是字符串,所以很有意义。
return str(date_list[0])
You can create a list of dates in string format using this method您可以使用此方法以字符串格式创建日期列表
[i.strftime("%Y-%m-%d") for i in pd.date_range(start=start_date, end=end_date)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.