Search code examples
pythondatedatetime

Datetime strptime in python (hours are not showing)


I have date format:

train_time = [01/01/2021 00:00
01/01/2021 01:00
01/01/2021 02:00
01/01/2021 03:00
01/01/2021 04:00
01/01/2021 05:00
01/01/2021 06:00
01/01/2021 07:00
01/01/2021 08:00

I used this #train_time = [dt.datetime.strptime(date, "%d/%m/%Y %H:%M").date() for date in train_time ]

the output train_time
[datetime.date(2021, 1, 1),
 
 datetime.date(2021, 1, 1),
 datetime.date(2021, 1, 1),

 datetime.date(2021, 1, 1),
 datetime.date(2021, 1, 1),
 datetime.date(2021, 1, 1),
 datetime.date(2021, 1, 1),
 datetime.date(2021, 1, 1),
 datetime.date(2021, 1, 1),
 datetime.date(2021, 1, 1),
 datetime.date(2021, 1, 2),

 datetime.date(2021, 1, 2),

 datetime.date(2021, 1, 2),

The hours are not showing, how I can add the actual hour in the date format. any options that are availble to have proper format


Solution

  • You almost got it. If you remove date(), you will accomplish what you are looking for:

    tt = [dt.datetime.strptime(date, "%d/%m/%Y %H:%M") for date in train_time ]
    

    The reason you are not getting time part, because date() removes it. If you remove that, you will get the whole thing.

    >>> tt[5]
    datetime.datetime(2021, 1, 1, 5, 0)
    >>> tt[5].date()
    datetime.date(2021, 1, 1)
    >>> tt[5].time()
    datetime.time(5, 0)