为了账号安全,请及时绑定邮箱和手机立即绑定

对于 1970-01-01 之前的日期,Windows 上的 datetime timestamp

对于 1970-01-01 之前的日期,Windows 上的 datetime timestamp

阿晨1998 2021-10-26 15:59:57
我目前正在尝试通过将日期转换为时间戳来在数据集中生成数字特征。如果在 Mac 上运行,它可以完美运行,在 Windows 上它会抛出:OS Error: [Errno 22] Invalid argument这可能是由于 Windows不支持 1970-01-01 之前的 unix 时间戳。我有 1955 年以上的日期。这是我的代码:import timeimport datetimecurrent_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(),但我不知道如何集成它。
查看完整描述

1 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

您可以通过(隐式)使用datetime.timedelta来计算“格里高利”时间戳,该时间戳对从 1582 年 10 月 15 日至今(或您想使用的其他“纪元”)的日期有效。


作为函数的文档字符串表示,日期字符串会在默认情况下,可以用一个解析'%Y-%m-%d' strptime式的格式字符串参数,但可以被覆盖。


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



查看完整回答
反对 回复 2021-10-26
  • 1 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信