Extract time from datetime in Python

Extract time from datetime in Python

In Python, if you have a datetime object, you can extract the time from it using the time() method. Here's how you can do it using the datetime module:

1. Extract Time from Current Datetime:

from datetime import datetime # Current datetime current_datetime = datetime.now() # Extract time current_time = current_datetime.time() print(current_time) 

2. Extract Time from a Specific Datetime:

from datetime import datetime # Given datetime given_datetime = datetime(2023, 10, 10, 15, 30, 45) # Example: October 10, 2023, 15:30:45 # Extract time given_time = given_datetime.time() print(given_time) # Output: 15:30:45 

The time() method returns a time object representing the time (hour, minute, second, microsecond). You can access these individual components using attributes like hour, minute, second, etc.

print(given_time.hour) # Output: 15 print(given_time.minute) # Output: 30 print(given_time.second) # Output: 45 

Remember that the extracted time will be in 24-hour format by default.


More Tags

progressive-web-apps listbox change-password ion-select uppercase popup-blocker new-operator w3c-validation jms-topic libraries

More Programming Guides

Other Guides

More Programming Examples