This article explains how to convert between Unix time (also known as Epoch time or Posix time) and the datetime object, which represents dates and times in Python.

Contents

What is Unix time (Epoch time, Posix time)?

Unix time is the number of seconds that have elapsed since the Unix epoch, 00:00:00 UTC (Coordinated Universal Time) on January 1, 1970. It is also known as Epoch time, Posix time, and so on.

Unix time (also known as Epoch time, Posix time, seconds since the Epoch, or UNIX Epoch time) is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970 (an arbitrary date). Unix time - Wikipedia

Convert Unix time (Epoch time) to datetime : fromtimestamp()

To work with dates and times in Python, use the datetime module.

  • Handle date and time with the datetime module in Python
  • Use datetime.fromtimestamp() from the datetime module to convert Unix time (Epoch time) to a datetime object. Pass Unix time as an argument.

  • datetime.datetime.fromtimestamp() — Basic date and time types — Python 3.11.3 documentation
  • By default, the conversion outputs the local date and time. For example, if your machine is set to Japan Standard Time (JST), the time difference (+9 hours) is considered.

    When 0 is passed as an argument:

    import datetime
    dt = datetime.datetime.fromtimestamp(0)
    print(dt)
    # 1970-01-01 09:00:00
    print(type(dt))
    # <class 'datetime.datetime'>
    print(dt.tzinfo)
    # None
    
    

    By default, the function returns a naive datetime object with the tzinfo attribute set to None.

    You can provide a second argument, tz, to specify a time zone. This will set the tzinfo attribute and return an aware datetime object with the date and time converted to the specified time zone.

  • datetime - timezone Objects — Basic date and time types — Python 3.11.3 documentation
  • dt_utc_aware = datetime.datetime.fromtimestamp(0, datetime.timezone.utc)
    print(dt_utc_aware)
    # 1970-01-01 00:00:00+00:00
    print(dt_utc_aware.tzinfo)
    # UTC
    dt_jst_aware = datetime.datetime.fromtimestamp(0, datetime.timezone(datetime.timedelta(hours=9)))
    print(dt_jst_aware)
    # 1970-01-01 09:00:00+09:00
    print(dt_jst_aware.tzinfo)
    # UTC+09:00
    
    

    datetime.utcfromtimestamp(), which returns a naive datetime object in UTC, where tzinfo is None, is also available.

  • datetime.datetime.utcfromtimestamp() — Basic date and time types — Python 3.11.3 documentation
  • dt_utc_naive = datetime.datetime.utcfromtimestamp(0)
    print(dt_utc_naive)
    # 1970-01-01 00:00:00
    print(dt_utc_naive.tzinfo)
    # None
    
    

    Convert datetime to Unix time (Epoch time): timestamp()

    Use the timestamp() method to convert a datetime object to Unix time (Epoch time). Unix time is returned as a floating point number (float).

  • datetime.datetime.timestamp() — Basic date and time types — Python 3.11.3 documentation
  • Consider the datetime object created by the sample code above.

    print(dt)
    # 1970-01-01 09:00:00
    print(dt.timestamp())
    # 0.0
    print(type(dt.timestamp()))
    # <class 'float'>
    
    

    Naive objects with the tzinfo attribute set to None are converted based on the environment's timezone, while aware objects with a defined tzinfo attribute are converted using their specific timezone.

    Note that the object created by utcfromtimestamp() is naive in UTC, meaning tzinfo is None, so the result is different from other objects.

    print(dt_utc_aware)
    # 1970-01-01 00:00:00+00:00
    print(dt_utc_aware.timestamp())
    # 0.0
    print(dt_jst_aware)
    # 1970-01-01 09:00:00+09:00
    print(dt_jst_aware.timestamp())
    # 0.0
    print(dt_utc_naive)
    # 1970-01-01 00:00:00
    print(dt_utc_naive.timestamp())
    # -32400.0
    
    

    If time zones are not a concern, you can disregard them since both the fromtimestamp() and timestamp() methods convert times based on the machine's local time by default.

  • Convert between isoformat string and datetime in Python
  • Get the current date and time in Python (datetime.now, date.today)
  • Get calendar as text, HTML, list in Python
  • Get file timestamp in Python (os.stat, os.path.getmtime, and more)
  • Measure elapsed time and time differences in Python
  • Determine, count, and list leap years in Python
  • Find the number of days and weeks of a month in Python
  • Handle date and time with the datetime module in Python
  • Lambda expressions in Python
  • NumPy: Create an empty ndarray with np.empty() and np.empty_like()
  • numpy.arange(), linspace(): Generate ndarray with evenly spaced values
  • List comprehensions in Python
  • Convert a list of strings and a list of numbers to each other in Python
  • How to install Python packages with pip and requirements.txt
  • Convert numpy.ndarray and list to each other
  • Convert between isoformat string and datetime in Python
  • Get the current date and time in Python (datetime.now, date.today)
  • Get calendar as text, HTML, list in Python
  • Get file timestamp in Python (os.stat, os.path.getmtime, and more)
  • Measure elapsed time and time differences in Python
  •