PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Python DateTime » Timestamp In Python

Timestamp In Python

Updated on: December 5, 2021 | 2 Comments

Python provides various libraries to work with timestamp data. For example, the datetime and time module helps in handling the multiple dates and time formats. In addition to this, it supports various functionalities involving the timestamp and timezone.

After reading this tutorial, you’ll learn: –

  • How to get the curent timestamp in Python
  • Convert timestamp to a datetime
  • Convert datetime to timestamp
  • Format timestamp to string object and vice-versa
  • How to get the timestamp object with an offset into a date-time object.

Table of contents

  • What is Timestamp in Python
  • Get Current Timestamp
    • Datetime to Timestamp
    • Get Timestamp Using time Module
    • Get Timestamp Using calendar Module
  • Convert Timestamp to Datetime (format)
  • Convert Timestamp to String
  • Get Timestamp in Milliseconds
  • Get The UTC timestamp
  • Timestamp from datetime with a Different Timezone
  • Convert an Integer Timestamp to Datetime

What is Timestamp in Python

A timestamp is encoded information generally used in UNIX, which indicates the date and time at which a particular event has occurred. This information could be accurate to the microseconds. It is a POSIX timestamp corresponding to the datetime instance.

In general, the date and time data are saved in the UNIX timestamp format. A UNIX time or Epoch or POSIX time is the number of seconds since the Epoch.

Unix time (also known as Epoch time, POSIX time, seconds since the Epoch, or UNIX Epoch time) describes a point in time.

It is the number of seconds that have elapsed since the Unix epoch, minus leap seconds.

The Unix epoch is 00:00:00 UTC on 1 January 1970 (an arbitrary date); leap seconds are ignored, with a leap second having the same Unix time as the second before it, and every day is treated as if it contains exactly 86400 seconds.

Wikipedia.

The reason we are using the UNIX epoch time as 1 January 1970 is because of the fact that UNIX came into business around that time frame.

The below image shows how a particular date and time is represented in different formats.

timestamp representation
timestamp representation

Get Current Timestamp

To get the current timestamp in Python, use any of the following three modules.

  • datetime
  • time
  • calendar

Datetime to Timestamp

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.
  • Next, pass the current datetime to the datetime.timestamp() method to get the UNIX timestamp

Example

from datetime import datetime

# Getting the current date and time
dt = datetime.now()

# getting the timestamp
ts = datetime.timestamp(dt)

print("Date and time is:", dt)
print("Timestamp is:", ts)Code language: Python (python)

Output:

Date and time is: 2021-07-03 16:21:12.357246
Timestamp is: 1625309472.357246

Note: Note: It returns timestamp in float type to get timestamp without decimal value convert it to an integer using the int(ts) constructor.

Get Timestamp Using time Module

The time module‘s time() method returns the current time in the timestamp format, which is nothing but the time elapsed from the epoch time, January 1, 1970.

  • First, import the time module
  • Next, use the time.time() method to get the timestamp

Definition: This function returns the time in seconds since the epoch as a floating-point number.

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347Code language: Python (python)

Get Timestamp Using calendar Module

Use the calendar module’s calendar.timegm() method to convert the current time to the timestamp.

  • First, import both time and the calendar modules.
  • Next, get the GMT time using the time module’s time.gmtime() method.
  • At last, pass it to the Use the calendar.timegm() method to get a timestamp

Example:

import calendar
import time

# Current GMT time in a tuple format
current_GMT = time.gmtime()

# ts stores timestamp
ts = calendar.timegm(current_GMT)
print("Current timestamp:", ts)

# output 1625310251Code language: Python (python)

Convert Timestamp to Datetime (format)

While the timestamp’s default format is just a floating-point number, there are cases when the timestamp will be represented in the ISO 8601 format. This looks something like the below value with the T and Z alphabets.

2014-09-12T19:34:29Z

Here the alphabet T stands for Time and Z stands for the Zero timezone which represents the offset from the coordinated universal time(UTC).

Let us see few examples with different date-time formats. Based on the format we will be using the format string and we can extract the timestamp information from that.

We can convert the timestamp back to datetime object using the fromtimestamp() method that is available in the datetime module.

Syntax

datetime.fromtimestamp(timestamp, tz=None)Code language: Python (python)

It returns the local date and time corresponding to the POSIX timestamp, such as is returned by time.time().

If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

Example:

from datetime import datetime

# timestamp
ts = 1617295943.17321

# convert to datetime
dt = datetime.fromtimestamp(ts)
print("The date and time is:", dt)

# output 2021-04-01 22:22:23.173210Code language: Python (python)

Convert Timestamp to String

We can convert the timestamp string using the datetime formatting.

  • First, convert the timestamp to a datetime instance.
  • Next, use the strftime() with formatting codes to convert timestamp to string format

It returns the local date and time corresponding to the POSIX timestamp, such as is returned by time.time().

If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

Example:

from datetime import datetime

timestamp = 1625309472.357246
# convert to datetime
date_time = datetime.fromtimestamp(timestamp)

# convert timestamp to string in dd-mm-yyyy HH:MM:SS
str_date_time = date_time.strftime("%d-%m-%Y, %H:%M:%S")
print("Result 1:", str_date_time)

# convert timestamp to string in dd month_name, yyyy format
str_date = date_time.strftime("%d %B, %Y")
print("Result 2:", str_date)

# convert timestamp in HH:AM/PM MM:SS
str_time = date_time.strftime("%I%p %M:%S")
print("Result 3:", str_time)Code language: Python (python)

Output:

Result 1: 03-07-2021, 16:21:12
Result 2: 03 July, 2021
Result 3: 04PM 21:12

Get Timestamp in Milliseconds

The datetime object comes with the timestamp which in turn could be displayed in milliseconds.

Example:

from datetime import datetime

# date in string format
birthday = "23.02.2012 09:12:00"

# convert to datetime instance
date_time = datetime.strptime(birthday, '%d.%m.%Y %H:%M:%S')

# timestamp in milliseconds
ts = date_time.timestamp() * 1000
print(ts)

# Output 1329968520000.0
Code language: Python (python)

Get The UTC timestamp

As we discussed, we can get the timestamp from the datetime object with the timezone information. We can convert a datetime object into a timestamp using the timestamp() method.

If the datetime object is UTC aware, then this method will create a UTC timestamp. If the object is naive, we can assign the UTC value to the tzinfo parameter of the datetime object and then call the timestamp() method.

Example: Get timestamp from datetime with UTC timezone

from datetime import datetime
from datetime import timezone

birthday = "23.02.2021 09:12:00"

# convert to datetime
date_time = datetime.strptime(birthday, '%d.%m.%Y %H:%M:%S')

# get UTC timestamp
utc_timestamp = date_time.replace(tzinfo=timezone.utc).timestamp()
print(utc_timestamp)

# Output 1614071520.0Code language: Python (python)

Timestamp from datetime with a Different Timezone

We have seen how to get the timestamp information from a datetime object with a timezone set as UTC.

Similarly, we can get timestamp information from a datetime object with a timezone different than the UTC. This could be done with strptime() with the offset information.

Read: Working with timezone in Python.

from datetime import datetime

# Timezone Name.
date_String = "23/Feb/2012:09:15:26 UTC +0900"
dt_format = datetime.strptime(date_String, '%d/%b/%Y:%H:%M:%S %Z %z')
print("Date with Timezone Name::", dt_format)

# Timestamp
timestamp = dt_format.timestamp()
print("timestamp is::", timestamp)Code language: Python (python)

Output

Date with Timezone Name:: 2012-02-23 09:15:26+09:00 
timestamp is:: 1329956126.0

Convert an Integer Timestamp to Datetime

We have seen how we can display the timestamp in milliseconds. Similarly, we can convert a timestamp value in integer to datetime object using the same fromtimestamp() or utcfromtimestamp() method.

In the below example we are considering the timestamp in milliseconds and finding its corresponding datetime object. We are using the constant le3 for normalizing the value.

Example:

import datetime

timestamp_int = 1329988320000
date = datetime.datetime.utcfromtimestamp(timestamp_int / 1e3)
print("Corresponding date for the integer timestamp is::", date)Code language: Python (python)

Output

Corresponding date for the integer timestamp is:: 2012-02-23 09:12:00

Filed Under: Python, Python DateTime

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python DateTime

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Richard says

    April 4, 2025 at 10:03 pm

    This is all indeed very useful.

    However, it doesn’t even mention files. OK, technically files don’t exist in UNIX ….
    But files do have various timestamps, depending on the operating system, namely:
    creation
    last modified
    last accessed

    The reason for bringing this up, is that most of the methods in python for writing these to the file handle only integers, whilst most means of getting them obtain them as datetime, to the millisecond. Hence, comparing an updated value to that obtained from a different file finds them unequal, as one is effectively truncated.

    A means of setting them to the millisecond would be really useful – having them here, which seems logical to me, would be exceptionally helpful. Perhaps a link to such an approach could be found and added?

    Reply
  2. Georg Korger says

    March 30, 2023 at 9:14 pm

    Hi Vishal!
    Thank you for your post. It saved me some time on my project.
    To speed up my code, i was interessed, which of the methods is the fastest to get an integer timestamp. I wrote the code below, tested it on a Desktop PC (Intel(R) Core(TM) i5-8500 CPU @ 3.00GHz) as well as on an old raspberry (1 or 2?!) using Python 3.9. It does 10000 iteration with each method.

    The result is, that the time.time() is by far the fastest one.

    Results of Desktop PC:
    #### using time
    1680189937.357511 1680189937.359478 Differenz: 1.9669532775878906 ms
    #### using datetime
    1680189937.789072 1680189937.799048 Differenz: 9.975910186767578 ms
    #### using calendar
    1680189938.252668 1680189938.264608 Differenz: 11.94000244140625 ms

    Result of RaspberryPi:
    #### using time
    1677675479.656541 1677675479.868345 Differenz: 211.80391311645508 ms
    #### using datetime
    1677675485.903571 1677675486.883357 Differenz: 979.7861576080322 ms
    #### using calendar
    1677675493.187282 1677675494.63502 Differenz: 1447.7379322052002 ms

    You may repost this comment, if you find it useful.

    Greetings from Austria
    George

    Code:
    print("#### using time")
    import time
    from datetime import datetime
    TI=list()
    startTI=datetime.timestamp(datetime.now())
    for i in range(0,10000):
    TI.append(int(time.time()))
    endTI=datetime.timestamp(datetime.now())

    for t in TI:
    print(t)

    print("#### using datetime")
    DT=list()
    startDT=datetime.timestamp(datetime.now())
    for i in range(0,10000):
    DT.append(int(datetime.timestamp(datetime.now())))
    endDT=datetime.timestamp(datetime.now())

    for t in DT:
    print(t)

    print("#### using calendar")
    import calendar
    CA=list()
    startCA=datetime.timestamp(datetime.now())
    for i in range(0,10000):
    CA.append(calendar.timegm(time.gmtime()))
    endCA=datetime.timestamp(datetime.now())

    for t in CA:
    print(t)

    print("#### using time")
    print(startTI,endTI,"Differenz:",(endTI-startTI)*1000,"ms")

    print("#### using datetime")
    print(startDT,endDT,"Differenz:",(endDT-startDT)*1000,"ms")

    print("#### using calendar")
    print(startCA,endCA,"Differenz:",(endCA-startCA)*1000,"ms")

    Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python DateTime
TweetF  sharein  shareP  Pin

 Python DateTime

  • Python DateTime Guide
  • Python Get Current DateTime
  • Python DateTime Formatting
  • Python String to DateTime
  • Python Timestamp
  • Python Timedelta
  • Python TimeZones
  • List All TimeZones in Python

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com