Get date from timestamp python

You can use date and time methods of the datetime class to do so:

>>> from datetime import datetime
>>> d = datetime.now()
>>> only_date, only_time = d.date(), d.time()
>>> only_date
datetime.date(2015, 11, 20)
>>> only_time
datetime.time(20, 39, 13, 105773)

Here is the datetime documentation.

Applied to your example, it can give something like this:

>>> milestone["only_date"] = [d.date() for d in milestone["datetime"]]
>>> milestone["only_time"] = [d.time() for d in milestone["datetime"]]

In this article, you will learn to convert timestamp to datetime object and datetime object to timestamp (with the help of examples).

It's pretty common to store date and time as a timestamp in a database. A Unix timestamp is the number of seconds between a particular date and January 1, 1970 at UTC.


Example 1: Python timestamp to datetime

from datetime import datetime

timestamp = 1545730073
dt_object = datetime.fromtimestamp(timestamp)

print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))

When you run the program, the output will be:

dt_object = 2018-12-25 09:27:53
type(dt_object) = 

Here, we have imported datetime class from the datetime module. Then, we used datetime.fromtimestamp() classmethod which returns the local date and time (datetime object). This object is stored in dt_object variable.

Note: You can easily create a string representing date and time from a datetime object using strftime() method.


Example 2: Python datetime to timestamp

You can get timestamp from a datetime object using datetime.timestamp() method.

from datetime import datetime

# current date and time
now = datetime.now()

timestamp = datetime.timestamp(now)
print("timestamp =", timestamp)

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Python has a module named DateTime to work with dates and times. We did not need to install it separately. It is pre-installed with the python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC.

    Timestamp to DateTime object

    You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.

    Syntax:

    fromtimestamp(timestamp, tz=None)

    Example: Python timestamp to DateTime

    Python3

    from datetime import datetime

    timestamp = 1545730073

    dt_obj = datetime.fromtimestamp(1140825600)

    print("date_time:",dt_obj)

    print("type of dt:",type(dt_obj))

    Output:

    date_time: 2006-02-25 05:30:00
    type of dt_obj: 
    

    Here, we have imported the DateTime class from DateTime module. Then we have used datetime.fromtimestamp() class method which returns the local DateTime. 

    To get a DateTime in a particular form in you can use strftime function. The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation.

    Example:

    Python3

    from datetime import datetime

    timestamp = 1553367060

    dt_obj = datetime.fromtimestamp(timestamp).strftime('%d-%m-%y')

    print("date:",dt_obj)

    Output:

    date: 24-03-19
    

    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.

    Advertisements

    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

    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
    
    

     

    How do I extract a date from a timestamp in Python?

    Python t date from a timestamp.
    from datetime import date..
    timestamp = date. fromtimestamp(1326244364).
    print("Date =", timestamp).

    How do I read a timestamp in Python?

    The timestamp() method of a datetime module returns the POSIX timestamp corresponding to the datetime instance. The return value is float. First, Get the current date and time in Python using the datetime. now() method.

    How do I convert timestamp to date?

    The constructor of the Date class receives a long value as an argument. Since the constructor of the Date class requires a long value, we need to convert the Timestamp object into a long value using the getTime() method of the TimeStamp class(present in SQL package).

    What is timestamp () Python?

    What is timestamp in Python? Timestamp is the date and time of occurrence of an event. In Python we can get the timestamp of an event to an accuracy of milliseconds. The timestamp format in Python returns the time elapsed from the epoch time which is set to 00:00:00 UTC for 1 January 1970.