Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 DateTimeIndexes containing Timestamps but sometimes seem to be something else (e.g. datetime.Date or numpy.datetime64).

Is there a generic way to check if a particular object is a date, i.e. any of the known date variable types? Or is that a function I should look to create myself?

Thanks!

like image 508
Chris Harris Avatar asked Oct 25 '25 23:10

Chris Harris


2 Answers

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')
like image 177
jpp Avatar answered Oct 28 '25 03:10

jpp


if isinstance(yourVariable,datetime.datetime):
   print("it's a date")
like image 25
AsankaJ Avatar answered Oct 28 '25 04:10

AsankaJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!