这是一个日期时间值数组:
array = np.array(['2016-05-01T00:00:59.3+10:00', '2016-05-01T00:02:59.4+10:00',
'2016-05-01T00:03:59.4+10:00', '2016-05-01T00:13:00.1+10:00',
'2016-05-01T00:22:00.5+10:00', '2016-05-01T00:31:01.1+10:00'],
dtype=object)
pd.to_datetime
非常擅长推断日期时间格式。
array = pd.to_datetime(array)
print(array)
DatetimeIndex(['2016-04-30 14:00:59.300000', '2016-04-30 14:02:59.400000',
'2016-04-30 14:03:59.400000', '2016-04-30 14:13:00.100000',
'2016-04-30 14:22:00.500000', '2016-04-30 14:31:01.100000'],
dtype='datetime64[ns]', freq=None)
如何动态确定 pd.to_datetime
推断出的日期时间格式?类似于:%Y-%m-%dT...
(抱歉,我的日期时间 foo 真的很糟糕)。
最佳答案
我认为在 pandas 中不可能做到这一点。
正如其他评论和答案中提到的,内部函数_guess_datetime_format
接近于您所要求的,但它对构成可猜测格式的内容有严格的标准,因此它仅适用于受限类的日期时间字符串。
这些标准在these lines 上的_guess_datetime_format
函数中列出。您还可以在 test_parsing 中看到一些好的和坏的格式示例。脚本。
一些要点是:
- 年、月、日都必须存在且可识别
- 年份必须为四位数
- 如果使用微秒,则必须使用六位数字
- 您不能指定时区
这意味着它无法猜测问题中日期时间字符串的格式,尽管它们是有效的 ISO 8601格式:
>>> from pandas.core.tools.datetimes import _guess_datetime_format_for_array
>>> array = np.array(['2016-05-01T00:00:59.3+10:00'])
>>> _guess_datetime_format_for_array(array)
# returns None
在这种情况下,删除时区并将微秒填充到六位数就足以让 pandas 识别格式:
>>> array = np.array(['2016-05-01T00:00:59.300000']) # six digits, no tz
>>> _guess_datetime_format_for_array(array)
'%Y-%m-%dT%H:%M:%S.%f'
这可能是最好的。
如果 pd.to_datetime
没有被要求推断数组的格式,或者给定一个格式字符串来尝试,它只会尝试分别解析每个字符串并希望它成功。至关重要的是,它不需要提前推断出格式。
首先,pandas 解析字符串,假设它是 (approximately) 一个 ISO 8601 格式。这始于对 _string_to_dts
的调用。并最终达到低级parse_iso_8601_datetime
完成艰苦工作的功能。
您可以使用 _test_parse_iso8601
来检查您的字符串是否能够以这种方式被解析。功能。例如:
from pandas._libs.tslib import _test_parse_iso8601
def is_iso8601(string):
try:
_test_parse_iso8601(string)
return True
except ValueError:
return False
您提供的数组中的日期被识别为这种格式:
>>> is_iso8601('2016-05-01T00:00:59.3+10:00')
True
但这并没有提供问题所要求的内容,而且我没有看到任何现实的方法来恢复 parse_iso_8601_datetime
函数识别的确切格式。
如果将字符串解析为 ISO 8601 格式失败,pandas 将回退到使用 parse()
来自第三方 dateutil 库的函数(由 parse_datetime_string
调用)。这提供了极好的解析灵 active ,但我不知道有什么好的方法可以从这个函数中提取可识别的日期时间格式。
如果 both 这两个解析器都失败了,pandas 要么引发错误,要么忽略字符串,要么默认为 NaT
(取决于用户指定的内容)。不再尝试解析字符串或猜测字符串的格式。
关于python - 日期时间转换 - 如何提取推断的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46842793/