Python is a versatile programming language that can be used for a variety of purposes. In this article, we will show you three ways to get current time in Python.
Get Current Time in Python with datetime module
In Python, the datetime module provides functions and classes for working with dates and times. The module provides classes for date, time, datetime, timedelta, and relativedelta. The functions in the module allow you to get the current time, to convert between different date and time formats, and to calculate the difference between two dates or times.
Here is one code example:
- import datetime
- print(datetime.datetime.now())
>>> from datetime import datetime
>>> now = datetime.now()
>>> print(“The current date is:”, now.strftime(“%Y-%m-%d %H:%M:%S”))
The current date is: 2022-02-20 10:19:14
>>> currentDT = datetime.now()
>>> print (“Current Year is: %d” % currentDT.year)
>>> print (“Current Month is: %d” % currentDT.month)
>>> print (“Current Day is: %d” % currentDT.day)
>>> print (“Current Hour is: %d” % currentDT.hour)
>>> print (“Current Minute is: %d” % currentDT.minute)
>>> print (“Current Second is: %d” % currentDT.second)
>>> print (“Current Microsecond is: %d” % currentDT.microsecond)
Here are four examples.
import datetime
currentDateTime = datetime.datetime.now()
print(currentDateTime)
———————————————————
from datetime import datetime
currentDateTime = datetime.now()
print(currentDateTime)
———————————————————
import datetime
print(datetime.datetime.now())
———————————————————
from datetime import datetime
print(datetime.now())
Get Current Time in Python with time module
The time module in Python provides a number of functions to work with dates and times. One of these is current_time(), which returns the current time as a datetime object. This can be useful for tracking the time in your code or generating reports.
>>> import time
>>> t = time.localtime()
>>> current_time = time.strftime(“%Y-%m-%d %H:%M:%S”, t)
>>> print(current_time)
2022-02-20 10:19:14
Get Current Time in Python with os module
Python comes with a handy module called os that can be used to get the current time. In this article, we will show you how to use the os module to get the current time in Python. We will also show you some examples of how to use the os module to get the current time in Python.
>>> import os
>>> os.system(‘date’)
Sun Feb 20 10:12:36 UTC 2022
>>> os.system(‘date +”%Y-%m-%d %H:%M:%S”‘)
2022-02-20 10:30:09