简体   繁体   中英

Checking if a python variable is a date?

One thing that I'm finding hard with the pandas/numpy combo is dealing with dates. My dataframe time series indices are often DateTimeIndex es containing Timestamps but sometimes seem to be something else (eg datetime.Date or numpy.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 . 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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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