Python Timestamp to Datetime and Vice Versa

Posted in /  

Python Timestamp to Datetime and Vice Versa
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    In this tutorial, we will learn how can we convert timestamp to datetime objects. In python, timestamp refers to the number of seconds from the epoch Unix time. In database, we often use the timestamp to refer the time. In python, we generally use Unix timestamp which is the number of seconds between a specific date and January 1, 1970, 00h: 00m: 00s at UTC.

    Python timestamp to datetime

    Example

    from datetime import datetime
    unix_timestamp = 1565694491   # number of seconds since 1 Jan 1970
    date_time_obj = datetime.fromtimestamp(unix_timestamp)
    print("Current date and time is: ",date_time_obj)
    print("type of date_time_obj is: ",type(date_time_obj))

    Output

    Current date and time is:  2019-08-13 16:38:11
    type of date_time_obj is:  <class 'datetime.datetime'>

    Behind the code

    In the above example, we have used the datetime.formtimestamp() function to convert the number of seconds to a datetime object date_time_obj . The unix_timestamp variable simply represents the number of seconds since the Unix timestamp which is 1 January 1970.

    Python datetime to timestamp

    In the above example, we have used the formtimestamp() function to convert the number of seconds to a particular date. Now we will use the timestamp() function to convert a particular date or current date to a number of seconds.

    Example

    from datetime import datetime
    today = datetime.today()
    unix_timestamp = datetime.timestamp(today)
    print("the value of unix_timestamp is ", unix_timestamp, "seconds since 1 Jan 1970")

    Output

    the value of unix_timestamp is  1565695158.213383 seconds since 1 Jan 1970

    Behind the code

    In the above example, we used the date.timestamp() function to convert the current date and time to Unix timestamp.

    Leave a Comment on this Post

    0 Comments