python - Windows 上 1970 年 1 月 1 日之前日期的 datetime timestamp() 解决方法

标签 python windows datetime timestamp

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

OS Error: [Errno 22] Invalid argument

这可能是由于 Windows not supporting unix timestamps from before 1970-01-01 。我有 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(),但我不知道如何集成它。

最佳答案

您可以通过(隐式)使用 datetime.timedelta 来做到这一点计算从 1582 年 10 月 15 日至今(或您想要使用的其他“纪元”)有效的“公历”时间戳。

正如函数的文档字符串所示,默认情况下,日期字符串将使用类似于 '%Y-%m-%d' strptimeformat string parameter 进行解析。 ,但这可以被覆盖。

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

关于python - Windows 上 1970 年 1 月 1 日之前日期的 datetime timestamp() 解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54470408/

相关文章:

python - 使用 ndimage 在 python 中旋转

python - 如果我将脚本命名为 'string.py' 或 'math.py',“导入”操作的行为会有所不同。为什么会这样?

windows - lua的字符串模式匹配为什么要这样做呢?

安卓 DatePicker- GregorianCalendar-00 :00:00 UTC - getTimeInMillis()

python - 为什么 Python 中的 08 或 09 无效?

python - 如何找到不同大小列表的中位数

php - 你能在 PHP 中获得 Windows (AD) 用户名​​吗?

c# - 等待进程完成然后显示消息 (C#)

c# - 每月最后一天加一天

javascript - 某些设备中的时区错误 - React Native