![](/img/trans.png)
[英]How to check if two dates falls between two columns of dataframe representing start date and end date
[英]How to check the date in between the tuple, dates as start and end
我有一個 function ,它在其中創建了一個字典,如下所示。
x = {'filename': {'filetype': ('5/6/2019', '12/31/2019')}, 'filename2': {'filetype': ('3/24/2018', '5/6/2019')}}
我需要通過傳遞日期及其類型來創建一個新的 function 以根據元組日期返回文件名。
def fn(date, filetype):
I'm trying to pass a date as a first argument
and the date should check if it is in between the tuple as start and end dates
in the dictionary values above If it is in between those dates I need to return the file name
return filename
問題:
是否可以檢查元組的中間日期?
您應該轉換為日期時間對象:
from datetime import datetime
x = {'filename': {'filetype': ('5/6/2019', '12/31/2019')}, 'filename2': {'filetype': ('3/24/2018', '5/6/2019')}}
def fn(dateobj, filetype):
dateobj = datetime.strptime(dateobj, '%m/%d/%Y')
startdate = datetime.strptime(filetype[0], '%m/%d/%Y')
enddate = datetime.strptime(filetype[1], '%m/%d/%Y')
return startdate <= dateobj <= enddate
print(fn('6/6/2019', x['filename']['filetype']))
print(fn('4/6/2019', x['filename']['filetype']))
這將打印:
True
False
正如人們在評論中提到的,建議將字符串日期轉換為日期時間對象。 一種方法是:
from datetime import datetime
new_date = datetime.strptime('12/31/2019', '%m/%d/%Y')
假設所有日期字符串都是日期時間對象,您的 function 變為:
def fn(date, filetype):
for filename, range in x.items():
if filetype in range:
start, end = range[filetype]
if start <= date <= end:
return filename
如果日期在范圍之間,這將返回文件名,否則返回 None
使用split
按以下順序將日期轉換為 3 個數值:年、月、日。 然后您可以將日期作為元組進行比較。
def convert(datestr):
m, d, y = datestr.split('/')
return (int(y), int(m), int(d))
date1 = convert('12/31/2018')
date2 = convert('1/1/2019')
print(date1 < date2)
相同的方法適用於列表,但是這兩種類型不能混合使用,比較中的所有日期都是元組,或者所有日期都是列表。
對於日期間隔,只需測試(例如在if
語句中):
begin <= date <= end
其中所有 3 個值都如上所述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.