Home > Software engineering >  pandas datetime with time format as 0:00:00 (h:mm:ss)
pandas datetime with time format as 0:00:00 (h:mm:ss)

Time:07-21

I`m looking to create a new row for a date with the following formatting:

2022-07-20 0:00:00

So basically, today's date and the time as h:mm:ss, all as 0

I'm trying to use pd.to_datetime('today') but the time is my current time and not 0. I also tried to use the same code but with .normalize() and then my time disappears, only the date remains.

Is there a way to do that?

CodePudding user response:

There are a few approaches you could take. I think in most cases it really depends on what you prefer, or what fits your use case best.

from datetime import datetime, date

datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

datetime.fromordinal(date.today().toordinal())

datetime.combine(date.today(), datetime.time(datetime.min))
>>> datetime.datetime(2022, 7, 20, 0, 0)
>>> datetime.datetime(2022, 7, 20, 0, 0)
>>> datetime.datetime(2022, 7, 20, 0, 0)

CodePudding user response:

If your dataframe is df, try:

from datetime import datetime
df['time'] = datetime.(year= ..., month= ..., day= ...)

CodePudding user response:

Perhaps I misunderstand, but does this do what you want?

import pandas as pd
dtrng = pd.date_range('2022-07-01', periods=31, freq='D')
df = pd.DataFrame({'Date' : dtrng})
df['DateTime'] = df.Date.dt.strftime('%Y-%m-%d %H:%M:%S')
df['DateHMSutc'] = pd.to_datetime(df['Date'], format='%Y-%m-%d %H:%M:%S', utc=True)
df.head()

    Date        DateTime                DateHMSutc
0   2022-07-01  2022-07-01 00:00:00     2022-07-01 00:00:00 00:00
1   2022-07-02  2022-07-02 00:00:00     2022-07-02 00:00:00 00:00
2   2022-07-03  2022-07-03 00:00:00     2022-07-03 00:00:00 00:00
3   2022-07-04  2022-07-04 00:00:00     2022-07-04 00:00:00 00:00
4   2022-07-05  2022-07-05 00:00:00     2022-07-05 00:00:00 00:00

df.dtypes

Date               datetime64[ns]
DateTime                   object
DateHMSutc    datetime64[ns, UTC]
dtype: object
  • Related