python - 从字符串中解析和组合日期和时间(闰秒) - python

标签 python date datetime time leap-second

我从包含多行日期的数据文件中解析日期(格式:YYYY-MM-DD HH:MM:SS)。

问题是数据包含闰秒,所以我无法使用datetime。我如何考虑闰秒 (0-60),以便在最后使用具有上述格式的字符串中的 datetime.strptime 得到相同的结果(因此,日期+时间),请问?

我已经尝试过使用 date 作为日期和 time 作为时间字符串来组合。这是正确的方法还是其他方法?

提前致谢。

最佳答案

只是use time.strptime() :

#!/usr/bin/env python
import datetime as DT
import time
from calendar import timegm

utc_time_string = '2012-06-30 23:59:60'
utc_time_tuple = time.strptime(utc_time_string, "%Y-%m-%d %H:%M:%S")[:6]
utc_dt = DT.datetime(1970, 1, 1) + DT.timedelta(seconds=timegm(utc_time_tuple))
# -> datetime.datetime(2012, 7, 1, 0, 0)

如果输入时间不是 UTC,那么您可以手动处理 time_tuple 中的闰秒,例如,datetime 模块可能会引发 ValueError 如果您直接传递闰秒,或者如果它在间接(内部)调用中遇到闰秒,它可能会默默地将 60 截断为 59

关于python - 从字符串中解析和组合日期和时间(闰秒) - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37299090/

相关文章:

python - 将数据插入数据库时​​PySpark NoSuchMethodError : sun. nio.ch.DirectBuffer.cleaner

python - 以元组为键解析字典

r - 根据 R 中另一列的日期范围查找一列的平均值

具有本地存储日期的智能手机(android,ios)的 HTML5 应用程序()

python - 创建交互变量的函数 : what is wrong with the code?

python - 有效读取大型、活跃的 Python 日志文件

以小时为单位的日期差异 - Angular 2

android - android.text.format.DateFormat 和 java.text.DateFormat 有什么区别

php - 将时间戳排序为间隔 PHP

日期组件操作