4

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!

2
  • Doesnt seem to be. Why not just create your own function that checks for any those types? Commented Feb 1, 2018 at 1:08
  • Some other ways can be found here: stackoverflow.com/questions/44988301/… Commented Feb 1, 2018 at 2:07

3 Answers 3

4

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this is helpful. As a general practice do you try to keep all time formats as Timestamps, to keep things simple?
if i'm working with pandas, yes. it's guaranteed to understand it because you are using pandas to cast it. it also has a host of convenience features: pandas.pydata.org/pandas-docs/stable/generated/…
2
if isinstance(yourVariable,datetime.datetime):
   print("it's a date")

2 Comments

Thanks! - that works for timestamps but not for datetime.date so it's not perfect.
you can include multiple types, e.g. `isinstance(var, (datetime.datetime, np.datetime64, datetime.date))
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.