0

I have a field in a dataset activity['date time'] that is currently a string and has this format: "2021-05-20T03:36:34.760"

I've been trying to convert it to a date field without the time, so essentially dropping everything after the T.

I've tried the following and nothing has worked.

pd.to_datetime(activity['date time'])

This code changes the time to just 0, but I would want it to be dropped:

datetime.strptime(activity['date time'], '%Y-%m-%d')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Donut
  • 53
  • 3

1 Answers1

1

here's a couple of options if you're using pandas.

import pandas as pd 

activity = pd.DataFrame({"date time": ["2021-05-20T03:36:34.760"]})

# this gives you only the date as string:
activity["date_str"] = activity["date time"].str.split("T").str[0]

# this gives you datetime data type:
activity["dt"] = pd.to_datetime(activity['date time'])

# this floors to the date / sets time zero:
activity["dt"] = activity["dt"].dt.floor("d")

# this gives you a Python date object column:
activity["date_obj"] = activity["dt"].dt.date
activity
                 date time    date_str         dt    date_obj
0  2021-05-20T03:36:34.760  2021-05-20 2021-05-20  2021-05-20
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • thanks for the response. I want the final result to be a datetime data type, without the time. I'm using pandas but open to other methods. I've tried your first option that splits the string to only keep the values before "T", and then tried converting that to datetime, but once I convert to datetime, it shows the time again as zero. I've also tried your second recommendation, and that doesn't drop the time for me and instead I end up with "2021-05-20T06:36:34.760000000" – Donut Mar 10 '23 at 15:47
  • @Donut if you're using pandas datetime, you cannot have date and time separately, it's always date *and* time. You'll have to just ignore the time portion. Not all dataframe libraries do it like this, e.g. with [polars](https://www.pola.rs/), you can choose from date, time and datetime. What library you use is of course dependent on your application. – FObersteiner Mar 10 '23 at 15:58