Popular Posts

Wednesday, February 15, 2023

Current Date & Time expression

Hello, Python developer!

Hope you're fine today! Do you know how can we express the current time in Python program?

Python has 'datetime' module for dealing with the date and time.

Let's test the it with following codes.


import datetime                                                # Load 'datetime' module
current_date_time = datetime.datetime.now( )        # Get current date & time
print(current_date_time)                                    #Print current date & time

Run result



If you want to add time or date about current date & time by datetime.now( ) function, please use 'timedelta' function. 

Here are 'timedelta' function examples.


import datetime
current_date_time = datetime.datetime.now( )
print( current_date_time + datetime.timedelta(seconds = 75))    # Add 75 seconds
print( current_date_time - datetime.timedelta(minutes = 25))    # Sub 25 minutes
print( current_date_time + datetime.timedelta(hours =7))        # Add 7 hours
print( current_date_time - datetime.timedelta(days=100))        # Sub 100 days
print( current_date_time + datetime.timedelta(weeks = 8))        # Add 8 weeks


Run result

As you recognized the above result, 'timedelta' function automatically converts seconds to minutes, minutes to hours, hours to days and days to weeks.

Please refer following 'datetime' reference documentation from Python official site.


In this reference page, you also find 'datetime' and 'timedelta' function explanation as following.

I hope you get to know and deal with date & time in Python.

Please take care and have a nice day, Python developer!  

No comments:

Post a Comment

Python - Web crawling exercises

Hello Python developer! How are you? Hope you've been good and had wonderful time with Python. There are 10 Python requests module exerc...