How to split current date time and retrieve only date , hour and minute?

Viewed 139
current_time = datetime.datetime.now()
print("current time ", current_time)

Result:

current time  2021-03-08 23:22:59.912410

Here, I want only up to minutes(2021-03-08 23:22) and need to get rid of seconds and milliseconds from the current time. Please help

2 Answers

You can use strftime() to output dates on a specific format, i.e.:

import datetime

current_time = datetime.datetime.now()
print("current time ", current_time.strftime("%Y-%m-%d %H:%M:%S"))
# current time 2021-03-09 04:42:57

Demo

You have to re-format the time in string as per the format you want.

formatted = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)

Output will be like:

'2021-03-09 10:12:58'

It also changes the datetime object to str. And hence datetime operations can not be performed on it. It is recommended to use only for output presentation.

Related