Get Seconds, Minutes and Hours from datetime

RN Rajesh Nallamothu 1 402 0.33 index 12/13/2021

datetime module in Python is used to get the date and time

we have to import it

from datetime import datetime

If we want to get the current datetime, we have use now() command

Syntax:

datetime.now()

Example:

  • Python program to display current datetime
#import datetime module
from datetime import datetime
#get the datetime
print(datetime.now())

Output:

2021-12-13 14:32:34.614845

Get hours

We can get hours using hour keyword

datetime.now().hour

Get minutes

We can get minutes using minute keyword

datetime.now().minute

Get seconds

We can get seconds using second keyword

datetime.now().second

Code:

#import datetime module
from datetime import datetime
#get hours
print(datetime.now().hour)
#get minutes
print(datetime.now().minute)
#get seconds
print(datetime.now().second)

Output:

14
35
51

python

Join the Discussion

View or add your thoughts below

Comments