0

I am using pd.to_datetime(df_upload['date_field']).dt.date to get just a date from datetime object. But result of this code is indeed object type. How do I get just a date from datetime object but with data type as date not object?

dan
  • 373
  • 2
  • 5
  • 24

1 Answers1

0

It is date, check type:

out = pd.to_datetime(df_upload['date_field']).dt.date

print (out.iat[0])
print (type(out.iat[0]))

If need datetimes without times, it means times are 00:00:00:

out = pd.to_datetime(df_upload['date_field']).dt.normalize()
out = pd.to_datetime(df_upload['date_field']).dt.floor('d')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • I could not understand your first comment. Should output of `pd.to_datetime(df_upload['date_field']).dt.date` be also date type, because in my case it is not? – dan Nov 05 '21 at 10:31
  • `normalize()` and `floor` are still giving `time` alongwith the `date`. – dan Nov 05 '21 at 10:42
  • @dan - no, type and dtype is different in pandas, check [this](https://stackoverflow.com/questions/42672552/pandas-cast-column-to-string-does-not-work/42672574#42672574) - similar is for dtype=object and type=date – jezrael Nov 05 '21 at 10:43
  • But with `dt.date` I am getting `string` as output, any easier way I can change it to `date` without `time`? – dan Nov 05 '21 at 10:45
  • @dan - no, ther is no string, it is type='date', check `print (type(out.iat[0]))` – jezrael Nov 05 '21 at 10:46
  • It is `date type`, correct,. But when I am uploading it to `SQL` table it is showing me string type. SQL is messing up the type here. thanks for your help. – dan Nov 05 '21 at 10:56
  • @dan - second solution didnt work? – jezrael Nov 05 '21 at 10:58
  • for second solution when I connect to SQL, it is in date format. but drawback is it is also displaying time along with the given date value. – dan Nov 05 '21 at 11:12
  • @dan - Can you check [this](https://stackoverflow.com/a/25166280/2901002) ? – jezrael Nov 05 '21 at 11:19
  • 1
    yes, i think this exacltly is the isseu, thank you very muchh. – dan Nov 05 '21 at 13:18