Python Forum

Full Version: Does a pandas have a date without a time?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
When I create a series object, I specify the type without time: 'datetime64[D]'. But when I look at the data type of this series in the debugger, I see the presence of time: 'datetime64[ns]'.

Things get even worse when I start plotting: the empty time is reflected in the chart as zeros: 2020-04-05 00:00:00 Angry

How to get rid of the time and leave only the date?
shorten ?

my_date = "2020-04-05 00:00:00"[:10]
print(my_date)
(Feb-03-2021, 01:54 PM)Axel_Erfurt Wrote: [ -> ]shorten ?

my_date = "2020-04-05 00:00:00"[:10]
print(my_date)

How do you propose to apply this to datetime64 data types stored in a dataframe?
I've tried to reproduce your issue, but in almost all my cases I do not get the time at all if I don't want to. I usually prefer to work with the 'standard' datetime object, which works fine as an object as dtype. But when I set the dtype to datetime64 it also works as expected. So datetime64[D] will return a date and datetime[ns] will return date and time.

Do you have an example of your code and an example of the DateFrame or Series you're using?
Can use dt.normalize().
Example.
import pandas as pd

url = 'http://bit.ly/uforeports'
df = pd.read_csv(url)
df['Time'] = pd.to_datetime(df.Time)
print(df.head())
Output:
City Colors Reported ... State Time 0 Ithaca NaN ... NY 1930-06-01 22:00:00 1 Willingboro NaN ... NJ 1930-06-30 20:00:00 2 Holyoke NaN ... CO 1931-02-15 14:00:00 3 Abilene NaN ... KS 1931-06-01 13:00:00 4 New York Worlds Fair NaN ... NY 1933-04-18 19:00:00
>>> df['Time'] = df['Time'].dt.normalize()
>>> df.head()
                   City Colors Reported Shape Reported State       Time
0                Ithaca             NaN       TRIANGLE    NY 1930-06-01
1           Willingboro             NaN          OTHER    NJ 1930-06-30
2               Holyoke             NaN           OVAL    CO 1931-02-15
3               Abilene             NaN           DISK    KS 1931-06-01
4  New York Worlds Fair             NaN          LIGHT    NY 1933-04-18
There is dt which has date:

>>> import pandas as pd
>>> df = pd.DataFrame(pd.date_range("2021-01-01", periods=3, freq="s"))
>>> df
                    0
0 2021-01-01 00:00:00
1 2021-01-01 00:00:01
2 2021-01-01 00:00:02
>>> df[0].dt.date
0    2021-01-01
1    2021-01-01
2    2021-01-01
Name: 0, dtype: object
>>> df[0].dt.year
0    2021
1    2021
2    2021
Name: 0, dtype: int64
>>> df[0].dt.day
0    1
1    1
2    1
Name: 0, dtype: int64
Please go through the following links at stackoverflow, I hope it will help you out:
/questions/16176996/keep-only-date-part-when-using-pandas-to-datetime
/questions/29310116/removing-time-from-datetime-variable-in-pandas