How to Get Current Date and Time using Python
In this article, we will cover different methods for getting data and time using the DateTime module and time module in Python.
Different ways to get Current Date and Time using Python
- Current time using DateTime object
- Get time using the time module
Get Current Date and Time Using the Datetime Module
In this example, we will learn How to get the current Date and Time using Python. In Python, date and time are not data types of their own, but a module named DateTime can be imported to work with the date as well as time. Datetime module comes built into Python, so there is no need to install it externally. To get both current date and time datetime.now() function of DateTime module is used. This function returns the current local date and time.
Current date-time using DateTime
In this example, we will use the DateTime object for getting the date and time using datetime.now().
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Time now at greenwich meridian is:", current_time)
Output:
Time now at greenwich meridian is: 2022-06-20 16:06:13.176788
Time complexity: O(1)
Auxiliary space: O(1)
Attributes of DateTime using DateTime
timedate.now() have different attributes, same as attributes of time such as year, month, date, hour, minute, and second.
# Python3 code to demonstrate
# attributes of now()
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing attributes of now().
print("The attributes of now() are :")
print("Year :", current_time.year)
print("Month : ", current_time.month)
print("Day : ", current_time.day)
print("Hour : ", current_time.hour)
print("Minute : ", current_time.minute)
print("Second :", current_time.second)
print("Microsecond :", current_time.microsecond)
Output:
The attributes of now() are :
Year : 2022
Month : 6
Day : 20
Hour : 16
Minute : 3
Second : 25
Microsecond : 547727
Get a particular timezone using pytz and datetime
In this example, it can be seen that the above code does not give the current date and time of your timezone. To get the date and time for a particular timezone now() takes timezone as input to give timezone-oriented output time. But these time zones are defined in pytz library.
# for now()
import datetime
# for timezone()
import pytz
# using now() to get current time
current_time = datetime.datetime.now(pytz.timezone('Asia/Kolkata'))
# printing current time in india
print("The current time in india is :", current_time)
Output:
The current time in india is :
2019-12-11 19:28:23.973616+05:30
Get Current Time In UTC using datetime Module
UTC Stands for Coordinated Universal Time, These times are useful when you are dealing with Applications that have a global user for logging the events. You can get the current time in UTC by using the datetime.utcnow() method
from datetime import datetime
print("UTC Time: ", datetime.utcnow())
Output:
UTC Time: 2022-06-20 11:10:18.289111
Get Current Time in ISO Format using datetime
isoformat() method is used to get the current date and time in the following format: It starts with the year, followed by the month, the day, the hour, the minutes, seconds, and milliseconds.
from datetime import datetime as dt
x = dt.now().isoformat()
print('Current ISO:', x)
Output:
Current ISO: 2022-06-20T17:03:23.299672
Get the current time Using the time Module
The Python time module, allows you to work with time in Python. It provides features such as retrieving the current time, pausing the program’s execution, and so on. So, before we begin working with this module, we must first import it.
Get the current time using the time
Here, we are getting the current time using the time module.
import time
curr_time = time.strftime("%H:%M:%S", time.localtime())
print("Current Time is :", curr_time)
Output:
Current Time is : 16:19:13
Get Current Time In Milliseconds using time
Here we are trying to get time in milliseconds by multiplying time by 1000.
import time
millisec = int(round(time.time() * 1000))
print("Time in Milli seconds: ", millisec)
Output:
Time in Milli seconds: 1655722337604
Get Current Time In Nanoseconds using time
In this example, we will get time in nanoseconds using time.ns() method.
import time
curr_time = time.strftime("%H:%M:%S", time.localtime())
print("Current Time is :", curr_time)
nano_seconds = time.time_ns()
print("Current time in Nano seconds is : ", nano_seconds)
Output:
Current Time is : 16:26:52
Current time in Nano seconds is : 1655722612496349800
Get Current GMT Time using time
Green Mean Time, which is also known as GMT can be used by using time.gmtime() method in python just need to pass the time in seconds to this method to get the GMT
import time
# current GMT Time
gmt_time = time.gmtime(time.time())
print('Current GMT Time:\n', gmt_time)
Output:
Current GMT Time:
time.struct_time(tm_year=2022, tm_mon=6, tm_mday=20,
tm_hour=11, tm_min=24, tm_sec=59, tm_wday=0, tm_yday=171, tm_isdst=0)
Get Current Time In Epoch using time
It is mostly used in file formats and operating systems. We can get the Epoch current time by converting the time.time() to an integer.
import time
print("Epoch Time is : ", int(time.time()))
Output:
Epoch Time is : 1655723915
How to Get Current Date and Time using Python – FAQs
How Do You Get the Current Date with a Specific Time in Python?
To get the current date with a specific time in Python, you can use the
datetime
module to combine today’s date with a specific time:Example:
from datetime import datetime, time
# Get today's date
today = datetime.today().date()
# Specify a time
specific_time = time(15, 30) # 3:30 PM
# Combine today's date with the specific time
datetime_with_specific_time = datetime.combine(today, specific_time)
print(datetime_with_specific_time) # Output: YYYY-MM-DD 15:30:00
How to Get Current Date in dd mm yyyy Format in Python?
To format the current date in the “dd mm yyyy” format, use the
strftime
method from thedatetime
module:Example:
from datetime import datetime
# Get current date
current_date = datetime.now()
# Format the date
formatted_date = current_date.strftime('%d %m %Y')
print(formatted_date)
How to Get Current Date and Time as String in Python?
To obtain the current date and time as a string, use the
strftime
method to format the datetime object:Example:
from datetime import datetime
# Get current datetime
current_datetime = datetime.now()
# Convert to string
datetime_string = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
print(datetime_string)
How Do I Get the Current Date and Time in Python Flask?
In a Flask application, you can get the current date and time using the
datetime
module, similar to any other Python script:Example:
from flask import Flask
from datetime import datetime
app = Flask(__name__)
@app.route('/')
def home():
current_datetime = datetime.now()
return f"Current Date and Time: {current_datetime.strftime('%Y-%m-%d %H:%M:%S')}"
if __name__ == '__main__':
app.run()
How Do I Get the Day of a Specific Date in Python?
To find the day of the week for a specific date, use the
datetime
module and access thestrftime
method with the ‘%A’ format code, which returns the full weekday name:Example:
from datetime import datetime
# Create a specific date
specific_date = datetime(2023, 9, 5)
# Get the day of the week
day_of_week = specific_date.strftime('%A')
print(day_of_week) # Output: TuesdayThese methods provide various ways to handle and format dates and times in Python, useful for applications needing precise time and date operations