Python : How to get Current date and time or timestamp ?

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().

datetime.now(tz=None)

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.

from datetime import datetime

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

# Returns a datetime object containing the local date and time
dateTimeObj = datetime.now()

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

print(dateTimeObj)

Output

2018-11-18 09:32:36.435350

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

# Access the member variables of datetime object to print date & time information
print(dateTimeObj.year, '/', dateTimeObj.month, '/', dateTimeObj.day)
print(dateTimeObj.hour, ':', dateTimeObj.minute, ':', dateTimeObj.second, '.', dateTimeObj.microsecond)

Output:

2018 / 11 / 18
9 : 32 : 36 . 435350

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.

# Converting datetime object to string
dateTimeObj = datetime.now()

timestampStr = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S.%f)")

print('Current Timestamp : ', timestampStr)

Output:

Current Timestamp :  18-Nov-2018 (09:32:36.435350)

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.

dateTimeObj = datetime.now()

# get the date object from datetime object
dateObj = dateTimeObj.date()

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.

# Access the member variables of date object to print
print(dateObj.year, '/', dateObj.month, '/', dateObj.day)

# Print the date object
print(dateObj)

Output:

9 : 37 : 55 . 574360
09:37:55.574360

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

# Converting date object to string
dateStr = dateObj.strftime("%b %d %Y ")
print(dateStr)

Output:

Nov 18 2018

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.

# Returns a datetime object containing the local date and time
dateTimeObj = datetime.now()

# get the time object from datetime object
timeObj = dateTimeObj.time()

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.

# Access the member variables of time object to print time information
print(timeObj.hour, ':', timeObj.minute, ':', timeObj.second, '.', timeObj.microsecond)

# It contains the time part of the current timestamp, we can access it's member variables to get the fields or we can directly print the object too
print(timeObj)

Output:

9 : 44 : 41 . 921898
09:44:41.921898

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

timeStr = timeObj.strftime("%H:%M:%S.%f")

Contents of timeStr will be,

09:44:41.921898

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.

# Get the seconds since epoch
secondsSinceEpoch = time.time()

Convert seconds since epoch to struct_time i.e.

# Convert seconds since epoch to struct_time
timeObj = time.localtime(secondsSinceEpoch)

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

# get the current timestamp elements from struct_time object i.e.
print('Current TimeStamp is : %d-%d-%d %d:%d:%d' % (
timeObj.tm_mday, timeObj.tm_mon, timeObj.tm_year, timeObj.tm_hour, timeObj.tm_min, timeObj.tm_sec))

Output:

Current TimeStamp is : 18-11-2018 9:44:41

Get Current Timestamp using time.ctime()

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

def ctime(seconds=None)

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.

timeStr = time.ctime()

print('Current Timestamp : ', timeStr)

Output:

Current Timestamp :  Sun Nov 18 09:44:41 2018

Complete executable example is as follows,

import time

from datetime import datetime


def main():

    print('*** Get Current date & timestamp using datetime.now() ***')

    # Returns a datetime object containing the local date and time
    dateTimeObj = datetime.now()

    # Access the member variables of datetime object to print date & time information
    print(dateTimeObj.year, '/', dateTimeObj.month, '/', dateTimeObj.day)
    print(dateTimeObj.hour, ':', dateTimeObj.minute, ':', dateTimeObj.second, '.', dateTimeObj.microsecond)

    print(dateTimeObj)

    # Converting datetime object to string
    timestampStr = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S.%f)")
    print('Current Timestamp : ', timestampStr)

    timestampStr = dateTimeObj.strftime("%H:%M:%S.%f - %b %d %Y ")
    print('Current Timestamp : ', timestampStr)

    print('*** Fetch the date only from datetime object ***')

    # get the date object from datetime object
    dateObj = dateTimeObj.date()

    # Print the date object
    print(dateObj)

    # Access the member variables of date object to print
    print(dateObj.year, '/', dateObj.month, '/', dateObj.day)

    # Converting date object to string
    dateStr = dateObj.strftime("%b %d %Y ")
    print(dateStr)

    print('*** Fetch the time only from datetime object ***')

    # get the time object from datetime object
    timeObj = dateTimeObj.time()
    # Access the member variables of time object to print time information
    print(timeObj.hour, ':', timeObj.minute, ':', timeObj.second, '.', timeObj.microsecond)

    # It contains the time part of the current timestamp, we can access it's member variables to get the fields or we can directly print the object too
    print(timeObj)


    # Converting date object to string
    timeStr = timeObj.strftime("%H:%M:%S.%f")
    print(timeStr)

    print('*** Get Current Timestamp using time.time() ***')

    # Get the seconds since epoch
    secondsSinceEpoch = time.time()

    print('Seconds since epoch : ', secondsSinceEpoch)

    # Convert seconds since epoch to struct_time
    timeObj = time.localtime(secondsSinceEpoch)

    print(timeObj)

    # get the current timestamp elements from struct_time object i.e.
    print('Current TimeStamp is : %d-%d-%d %d:%d:%d' % (
    timeObj.tm_mday, timeObj.tm_mon, timeObj.tm_year, timeObj.tm_hour, timeObj.tm_min, timeObj.tm_sec))

    # It does not have the microsecond field

    print('*** Get Current Timestamp using time.ctime() *** ')

    timeStr = time.ctime()

    print('Current Timestamp : ', timeStr)


if __name__ == '__main__':
    main()

Output:

*** Get Current date & timestamp using datetime.now() ***
2018 / 11 / 18
9 : 44 : 41 . 921898
2018-11-18 09:44:41.921898
Current Timestamp :  18-Nov-2018 (09:44:41.921898)
Current Timestamp :  09:44:41.921898 - Nov 18 2018 
*** Fetch the date only from datetime object ***
2018-11-18
2018 / 11 / 18
Nov 18 2018 
*** Fetch the time only from datetime object ***
9 : 44 : 41 . 921898
09:44:41.921898
09:44:41.921898
*** Get Current Timestamp using time.time() ***
Seconds since epoch :  1542514481.9218981
time.struct_time(tm_year=2018, tm_mon=11, tm_mday=18, tm_hour=9, tm_min=44, tm_sec=41, tm_wday=6, tm_yday=322, tm_isdst=0)
Current TimeStamp is : 18-11-2018 9:44:41
*** Get Current Timestamp using time.ctime() *** 
Current Timestamp :  Sun Nov 18 09:44:41 2018

 

1 thought on “Python : How to get Current date and time or timestamp ?”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top