Python comes with built in functionality to access your OS’s current date and time. You can access these using the available datetime and date classes.
The following code access both the date and the time, and shows a comment of what each line of code does, and can come in handy when you need to access the current date or time, or when you need to work with functionality that requires some information on the date and time. This is easy in Python, as shown below.
# ============================================================================= # Accessing the current time, day of week, month, year # ============================================================================= from datetime import date from datetime import datetime def main(): # Access the date class to get the today() method, in order to get the current date theDate = date.today() print ("The current date is:", theDate) # Access the specific day, month and year for the current date print ("The day is:", theDate.day, "- the month is:", theDate.month, "- the year is:", theDate.year) # Acccess each day of the week - starts from 0 which represents # Monday, to 6 which represents Sunday) print ("Today is (Mon=0, Sun=6):", theDate.weekday()) daysOfWeek = ["Mon","Tues","Wedns","Thurs","Fri","Sat","Sun"] print ("Today is:", daysOfWeek[theDate.weekday()]) # Working with datetime # Access the current date from the datetime theDateAndTime = datetime.now() print ("The current date and time is:", theDateAndTime) # Access only the current time currentTime = datetime.time(datetime.now()) print ("The current time is:", currentTime) if __name__ == "__main__": main()
The output after running this is:
The current date is: 2020-05-30 The day is: 30 - the month is: 5 - the year is: 2020 Today is (Mon=0, Sun=6): 5 Today is: Sat The current date and time is: 2020-05-30 14:04:53.940994 The current time is: 14:04:53.940994
The date class can also be used to perform useful tasks with dates. For example, let’s say we want to know how many days left there are for July 1st. We can easily do this using the code below.
# ============================================================================= # Record how many days until this coming July 1st # ============================================================================= from datetime import date todaysDate = date.today() # record today's date julyFirst = date(todaysDate.year, 7, 1) # record the date of this coming July 1st daysUntilJulyFirst = julyFirst - todaysDate # record difference in time print ("It will be", daysUntilJulyFirst.days, "days until July 1st is here!")
The output is:
It will be 32 days until July 1st is here!
We can use the timedelta class to get the future date and time which is a certain number of days away. Let’s say we needed to get the exact date and time one year from now. We can do this using the following code.
# ============================================================================= # Record the date one year from now # ============================================================================= from datetime import timedelta print ("The date exactly one year from now will be", (now + timedelta(days=365)))
The output would be:
The date exactly one year from now will be 2021-05-30 14:44:41.482812
A useful feature you can add is to time how long it takes a code to run, from start to termination. This is especially useful when working the large datasets, where you can simply test the time it takes for Python to execute certain functions that involve dealing with time intensive tasks such as retrieving text data, text preprocessing tasks, running machine learning algorithms, etc. It is simple and effective way to compare the runtime of different pieces of code and work to make them more efficient. Efficiency is vital when working with data. The following code uses the time class in Python to record the initial execution time at the start of the program, and then right before it terminates, it would subtract the current time from the recorded time at the start of the program. This would give the total time of execution of the program.
# ============================================================================= # Using the time class to record the initial execution time, and then subtract # that from the end execution time. # ============================================================================= import time startExecutionTime = time.time() print("Run any script here..") print("~~~~~-Execution time: %s Seconds~~~~~" % (time.time() - startExecutionTime))
The output of this is:
Run any script here.. ~~~~~-Execution time: 0.0009815692901611328 Seconds~~~~~1