Get Seconds, Minutes and Hours from datetime

R Rajesh Nallamothu event 2021-12-13 visibility 369 comment 1
more_vert

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

More from Kontext
comment Comments
Administrator Administrator

Administrator access_time 3 years ago link more_vert

Hi Rajesh,

Good tutorial. One small suggestion - you can add Python to your article title so that others can find know it easily. 

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts