In this article we will discuss different ways to get the current date & timestamp in python.

Get the current date & time using datetime.now()

Python provides a module datetime which has a class datetime. It provides a method now().

It returns a datetime class object containing the current date & time information in provided timezone. If no timezone is provided then returned object will contain the current date time information in local timezone.

To use this we need to import datetime class from datetime module i.e.

Let’s use this to get the current date & timestamp i.e.

We can directly print this datetime object, it will display the data in readable format i.e.

Output

Now let’s access the member variables of datetime object to fetch the current timestamp elements like month , year, hour etc.

Output:

Instead of accessing each member of datetime object & creating a string of timestamp, we can directly convert the datetime object to different string formats. For example,

Let’s get the current timestamp & convert the datetime object to DD-MMM-YYYY (HH:MM::SS.MICROS) format i.e.

Output:

We will discuss datetime to string conversion in more details in next article.

Get the current Date only

Suppose we don’t want complete current timestamp, we are just interested in current date. How to do that ?

datetime class in datetime module consists of  2 other classes i.e date & time class. We can get date object from a datetime object i.e.

It contains the date part of the current timestamp, we can access it’s member variables to get the fields or we can directly and we can also print the object too i.e.

Output:

or we can convert it to string too i.e.

Output:

Get the current Time only

Now Suppose we are just interested in current time of today. How to do that?

As datetime module provides a datetime.time class too. We can get time object from a datetime object i.e.

It contains the time part of the current timestamp, we can access it’s member variables to get the fields or we can directly and we can also print the object too i.e.

Output:

or we can convert it to string too i.e.

Contents of timeStr will be,

Get Current Timestamp using time.time()

Python provides a module time & it has a function time() that returns the number of seconds that have elapsed since epoch i.e. January 1, 1970 i.e.

Convert seconds since epoch to struct_time i.e.

Now let’s access the member variables of struct_time object to create current timestamp in string format i.e.

Output:

Get Current Timestamp using time.ctime()

time module has another function time.ctime() i.e.

It accepts the seconds since epoch and convert them into a readable string format. If seconds are not passed it will take current timestamp i.e.

Output:

Complete executable example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.