如何比较来自两个不同来源且日期格式不同的日期字符串?

How to compare strings of dates that come from two different sources and dates are in different format?

我有两个包含“假期”列的数据框 - 值是日期字符串(日期范围)。 其中一个格式如下:2018-01-01_2018-01-03,2018-04-17_2018-05-05,2019-03-20_2019-03_21 在第二个中:01-JAN-18_03-JAN-18,17-APR-18_05-MAY-18,20-MAR-19_21-MAR-19

如何比较两个来源之间的日期是否匹配?

给你,为你找到解决方案的基础。

from datetime import datetime

def is_match(s1,s2) -> bool:
    for a,b in zip(s1.split("_"),s2.split("_")):
        d1 = datetime.strptime(a, "%Y-%m-%d")
        d2 = datetime.strptime(b, "%d-%b-%y")
        if d1 != d2: return False
    return True

assert is_match("2018-01-01_2018-01-03","01-JAN-18_03-JAN-18") == True
assert is_match("2019-01-01_2018-01-03","01-JAN-18_03-JAN-18") == False

如果您理解这一点,或者如果您需要提出任何进一步的问题,我希望您发表评论。好的来源:https://docs.python.org/3/library/datetime.html

拆分 '_' 上的每个字符串并将结果列表转换为 datetime。逐行比较您从该行获得的日期时间元组:

import pandas as pd

df = pd.DataFrame({'range0':['2018-01-01_2018-01-03','2018-04-17_2018-05-05','2019-03-20_2019-03-21', ''],
                   'range1':['01-JAN-18_03-JAN-18','17-APR-18_05-MAY-18','20-MAR-19_21-MAR-19', '']})

def equal_daterange(c0, c1, sep='_'):
    if c0 and c1: # make sure strings c0 and c1 are not empty
        r0 = pd.to_datetime(c0.split(sep))
        r1 = pd.to_datetime(c1.split(sep))
        return all(r0 == r1)
    return False # implicit else: strings c0 and/or c1 were empty

df['range_equal'] = df.apply(lambda x: equal_daterange(x['range0'], x['range1']), axis=1)
  
# df['range_equal']
# 0     True
# 1     True
# 2     True
# 3    False
# Name: range_equal, dtype: bool