Home > Software engineering >  How do I import a column as datetime.date?
How do I import a column as datetime.date?

Time:01-17

I have a dataset in CSV which first column are dates (not datetimes, just dates).

The CSV is like this:

date,text
2005-01-01,"FOO-BAR-1"
2005-01-02,"FOO-BAR-2"

If I do this:

df = pd.read_csv('mycsv.csv')

I get:

print(df.dtypes)

date       object
text       object
dtype: object

How can I get column date by datetime.date?

CodePudding user response:

You can use pd.to_datetime function available in pandas.

For example in a dataset about scores of a cricket match. I can convert the Matchdate column to datatime object by applying pd.to_datetime function based on the data time format given in the data. ( Refer https://www.w3schools.com/python/python_datetime.asp to assign commands based on your data time formating )

 cricket["MatchDate"]=pd.to_datetime(cricket["MatchDate"], format= "%m-%d-%Y") 

CodePudding user response:

Use:

df = pd.read_csv('mycsv.csv', parse_dates=[0])

This way the initial column will be of native pandasonic datetime type, which is used in Pandas much more often than pythonic datetime.date.

It is a more natural approach than conversion of the column in question after you read the DataFrame.

  •  Tags:  
  • Related