Chris Harris
Chris Harris

Reputation: 197

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!

Upvotes: 4

Views: 3701

Answers (3)

jpp
jpp

Reputation: 164673

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')

Upvotes: 4

AsankaJ
AsankaJ

Reputation: 102

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

Upvotes: 2

rekteridae
rekteridae

Reputation: 11

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/

Upvotes: 1

Related Questions