The Wayback Machine - https://web.archive.org/web/20241129165414/https://www.geeksforgeeks.org/get-current-date-and-time-using-python/
Open In App

How to Get Current Date and Time using Python

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

  1. Current time using DateTime object
  2. 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().

Python
# 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.

Python
# 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. 

Python
# 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

Python
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.

Python
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.

Python
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.

Python
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.

Python
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 

Python
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.

Python
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 the datetime 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 the strftime 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: Tuesday

These methods provide various ways to handle and format dates and times in Python, useful for applications needing precise time and date operations



Previous Article
Next Article

Similar Reads

Get current date using Python
Prerequisite: DateTime module 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. The DateTime module provides some functions to get the current date as well as time. Get the
3 min read
Get current time in milliseconds using Python
In this article, we will get the time in milliseconds using Python. Here, we are using two inbuild modules of Python that is Datetime module and the Time Module to get the time in milliseconds. Get time in milliseconds using the DateTime module To get the time in milliseconds we used the DateTime module, Firstly we printed the date time with second
2 min read
Get Current Time in different Timezone using Python
Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world's standard for time zone. In order to get the current time of different time zones, we will be using the pyt
4 min read
How to get file creation and modification date or time in Python?
We often need to access various file properties for different purposes. Among the file properties, the creation and modification time of a file are the most commonly used ones. We can achieve the same functionality and use it for various utility purposes, using multiple methods. You can use functions from the time module and datetime module to get
4 min read
Get parent of current directory using Python
In Python, OS module is used to interact with the operating system. It comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. OS module provides various ways for getting the parent di
4 min read
Get current Gold price using Python
In this article we will see how we can get the current gold price in India. There is a variation in price of gold with time to time, price of gold is moved by a combination of supply, demand, and investor behavior. That seems simple enough, yet the way those factors work together is sometimes counterintuitive. Modules required and Installation: Req
2 min read
Python - Get Today's Current Day using Speech Recognition
We often don't remember the day of the date due to our load of work we are doing. So, here is a Python program with the help of which we can find the day of the date with just a simple chat with our laptop or mobile. Modules NeededDateTime: This is a Library in Python with the help of which we can manipulate the date and time. It comes preinstalled
4 min read
Get Current Timestamp Using Python
A timestamp is a sequence of characters that represents the date and time at which a particular event occurred, often accurate to fractions of a second. Timestamps are essential in logging events, tracking files, and handling date-time data in various applications. Here, we will learn how to get the current timestamp in Python. How to Get the Curre
3 min read
How to get current CPU and RAM usage in Python?
CPU usage or utilization refers to the time taken by a computer to process some information. RAM usage or MAIN MEMORY UTILIZATION on the other hand refers to the amount of time RAM is used by a certain system at a particular time. Both of these can be retrieved using Python. Get current CPU usage in PythonGet current CPU usage using psutil The func
3 min read
Python VLC MediaPlayer - Getting Current media time
In this article we will see how we can get current media time of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. We can crea
2 min read
How to add hours to the current time in Python?
Prerequisites: Datetime module Every minute should be enjoyed and savored. Time is measured by the hours, days, years, and so on. Time helps us to make a good habit of organizing and structuring our daily activities. In this article, we will see how we can extract real-time from a python module. There are various ways to pass the date and time feat
3 min read
How to Get directory of Current Script in Python?
A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management. In this article, we will take a look at methods used for obtaining the Parent directory of the currently running python script, and would learn about va
4 min read
Get Current Value Of Generator In Python
Python generators are powerful constructs that allow lazy evaluation of data, enabling efficient memory usage and improved performance. When working with generators, it's essential to have tools to inspect their current state. In this article, we'll explore some different methods to get the current value of a generator in Python. Get Current Value
3 min read
Get Current directory in Python
In this article, we will cover How to Get and Change the Working Directory in Python. While working with file handling you might have noticed that files are referenced only by their names, e.g. 'GFG.txt' and if the file is not located in the directory of the script, Python raises an error. The concept of the Current Working Directory (CWD) becomes
3 min read
How to get the current username in Python
When building interacting Python programs you might need to get the current username for features like personalizing user experience, providing user-specific resources, Implementing robust logging and debugging, strengthening security, etc. We will use different Python modules and functions like os.getlogin(), os.path.expanduser(), environ.get() me
4 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Display date and time in videos using OpenCV - Python
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. It can process images and videos to identify objects, faces, or even the handwriting of a humanNote: For more information, refer to Introduction to OpenCV Display date and time in videos It sometimes becomes necessary to display date and time on videos when we
2 min read
Python | Working with date and time using Pandas
While working with data, encountering time series data is very usual. Pandas is a very useful tool while working with time series data.  Pandas provide a different set of tools using which we can perform all the necessary tasks on date-time data. Let's try to understand with the examples discussed below. Working with Dates in PandasThe date class i
8 min read
How to print date starting from the given date for n number of days using Pandas?
In this article, we will print all the dates starting from the given date for n number days. It can be done using the pandas.date_range() function. This function is used to get a fixed frequency DatetimeIndex. Syntax: pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None, **kwargs) Approac
2 min read
Pandas Series dt.time | Extract Time from Time Stamp in Series
The Series.dt.time attribute returns a NumPy array containing time values of the timestamps in a Pandas series. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime
2 min read
PYGLET – Get Current Media Texture in Player
In this article, we will see how we can get current media texture of player of PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia, etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to
3 min read
Get current number of partitions of a DataFrame - Pyspark
In this article, we are going to learn how to get the current number of partitions of a data frame using Pyspark in Python. In many cases, we need to know the number of partitions in large data frames. Sometimes we have partitioned the data and we need to verify if it has been correctly partitioned or not. There are various methods to get the curre
6 min read
Get the Current URL within a Django Template
Django, a high-level Python web framework, encourages rapid development and clean, pragmatic design. One common requirement when developing web applications is to access the current URL within a template. This can be useful for various purposes such as highlighting the active link in a navigation menu or generating dynamic content based on the URL.
3 min read
Get Yesterday's date using Python
Prerequisite: datetime moduleIn Python, date and time are not a data type of its 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 work with date, datetime module provides the date class and timedelta class is used to calc
2 min read
Manipulate Date and Time with the Datetime Module in Python
Have you ever wondered about working with Date and Time with Python? If you have then you must have noticed that Python does not provide any built-in method to work with either Date or Time. But thanks to the DateTime module that comes pre-loaded with Python's standard utility modules we can easily manipulate date and time according to our own need
9 min read
Python Tweepy – Getting the date and time when a tweet was tweeted
In this article we will see how we can get the date and time when a status/tweet was posted/tweeted. The created_at attribute of the Status object provides us with a datetime object which tell us when the status was posted. Identifying the date when a status was posted in the GUI : In the above mentioned status, the status was posted on : Jun 11 In
2 min read
How to convert date and time with different timezones in Python?
In this article, we will discuss how to convert date and time with different timezones in Python. To do this we will use one of the modules of python pytz . This module brings the Olson tz database into Python and this library allows accurate and cross-platform timezone calculations using Python. The method pytz.timezone() generates the current tim
2 min read
Get month and Year from Date in Pandas - Python
Pandas is one of the most powerful library in Python which is used for high performance and speed of calculation. It is basically an open-source BSD-licensed Python library. Commonly it is used for exploratory data analysis, machine learning, data visualization in data science, and many more. It has very dynamic and easy to understand syntax which
4 min read
Pandas Series dt.date | Extract Date From DateTime Objects
The dt.date attribute extracts the date part of the DateTime objects in a Pandas Series. It returns the NumPy array of Python datetime.date objects, mainly the date part of timestamps without information about the time and timezone. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '201
2 min read
Get Real-time Crypto Price Using Python And Binance API
In this article, we are going to see how to get the real-time price of cryptocurrencies using Binance API in Python. Binance API Binance API is a method that allows you to connect to the Binance servers using several programming languages. With it, you can automate your trading and make HTTP requests to send and receive data. Here we access Binance
2 min read
three90RightbarBannerImg