栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您可以通过(隐式)使用

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

正如函数的文档字符串所指示的那样,默认情况下,日期字符串将使用

'%Y-%m-%d'

strptime
-like格式字符串参数进行解析,但可以覆盖该参数。

from datetime import datetimeGREGORIAN_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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/420013.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号