Windows上日期为1970-01-01之前的datetime timestamp()的变通办法

发布于 2021-01-29 14:55:26

我目前正在尝试通过将日期转换为时间戳来在数据集中生成数字特征。如果在Mac上运行,它可以完美运行,在Windows上,它会抛出:

OS Error: [Errno 22] Invalid argument

这可能是由于Windows不支持1970-01-01之前的unix时间戳。我的约会日期从1955年开始。这是我的代码:

import time
import datetime

current_timestamp = time.time()
df.loc[:, "FEATURE_num"] = df["FEATURE"].apply(lambda d: datetime.datetime.strptime(d, '%Y-%m-%d').timestamp() if isinstance(d, str) else current_timestamp)

我在某处看到建议使用datetime.timedelta(),但我不知道如何集成它。

关注者
0
被浏览
117
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以通过(隐式)使用datetime.timedelta计算“格雷戈里”时间戳来实现,该时间戳对于从1582年10月15日到现在的日期(或您想使用的其他“时代”)有效。

    正如函数的文档字符串所指示的那样,默认情况下,日期字符串将使用'%Y-%m-%d'
    strptime-like格式字符串参数进行解析,但可以覆盖该参数

    from datetime import datetime
    
    
    GREGORIAN_EPOCH = datetime.strptime('1582-10-15', '%Y-%m-%d')
    
    
    def gregorian_timestamp(date, format='%Y-%m-%d'):
        """ Calculate timestamp using start of Gregorian calender as epoch.
    
            The date parameter can be either a string or a datetime.datetime
            object. Strings will be parsed using the '%Y-%m-%d' format by default
            unless a different one is specfied via the optional format parameter.
        """
        try:
            date = datetime.strptime(date, format)
        except TypeError:
            pass
        return (date - GREGORIAN_EPOCH).total_seconds()  # The timedelta in seconds.
    
    
    if __name__ == '__main__':
    
        current_date = datetime.now()
        timestamp = gregorian_timestamp(current_date)
        print('gregorian timestamp:', timestamp)  # -> gregorian timestamp: 13768250461.136208
    
        timestamp = gregorian_timestamp('1970-01-01')
        print('gregorian timestamp:', timestamp)  # -> gregorian timestamp: 12219292800.0
    
        timestamp = gregorian_timestamp('1955-02-28')
        print('gregorian timestamp:', timestamp)  # -> gregorian timestamp: 11750918400.0
    
        timestamp = gregorian_timestamp('1582-10-15')
        print('gregorian timestamp:', timestamp)  # -> gregorian timestamp: 0.0
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看