简体   繁体   English

检查python变量是否为日期?

[英]Checking if a python variable is a date?

One thing that I'm finding hard with the pandas/numpy combo is dealing with dates. 我用pandas / numpy组合很难找到的一件事是处理日期。 My dataframe time series indices are often DateTimeIndex es containing Timestamps but sometimes seem to be something else (eg datetime.Date or numpy.datetime64 ). 我的dataframe时间序列索引通常是包含Timestamp的DateTimeIndex ,但有时似乎是其他内容(例如datetime.Datenumpy.datetime64 )。

Is there a generic way to check if a particular object is a date, ie any of the known date variable types? 是否有通用的方法来检查特定对象是否为日期,即任何已知的日期变量类型? Or is that a function I should look to create myself? 还是我应该创建自己的功能?

Thanks! 谢谢!

I use this function to convert a series to a consistent datetime object in pandas / numpy . 我使用此函数将系列转换为pandas / numpy一致的datetime对象。 It works with both scalars and series. 它适用于标量和系列。

import pandas as pd
x = '2018-12-11'
pd.to_datetime(x)  # Timestamp('2018-12-11 00:00:00')

I would try converting the string representation of what I suspect to be a datetime into a datetime object , using the parse function from dateutil.parser . 我将尝试使用dateutil.parser中parse函数将我怀疑是datetime的字符串表示形式转换为datetime对象

https://chrisalbon.com/python/basics/strings_to_datetime/ https://chrisalbon.com/python/basics/strings_to_datetime/

if isinstance(yourVariable,datetime.datetime):
   print("it's a date")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM