PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python DateTime » Timestamp In Python

Timestamp In Python

Updated on: December 1, 2026 | 2 Comments

A timestamp is the simplest way for a computer to store a moment in time: a single number. Databases, log files, APIs, and file systems use timestamps everywhere. Python’s datetime and time modules make it easy to get a timestamp and to convert it to and from readable dates.

This article is part of a series on Python Date and Time.

After reading this tutorial, you’ll learn:

  • What a Unix timestamp is.
  • How to get the current timestamp in Python.
  • How to convert a timestamp to a datetime, and a datetime to a timestamp.
  • How to format a timestamp as a string, and convert a string to a timestamp.
  • How to work with timestamps in milliseconds and with UTC and other timezones.

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
    • Get timestamp from datetime with UTC timezone
  • Timestamp from datetime with a Different Timezone
  • Convert an Integer Timestamp to Datetime
  • Calculate Time Difference Using Timestamps
  • Summary

What is Timestamp in Python

A Unix timestamp (also called Epoch time or POSIX time) is the number of seconds that have passed since 00:00:00 UTC on 1 January 1970. That starting point is called the Unix epoch. It was chosen as a convenient round date when the Unix operating system was being developed.

For example, the timestamp 1625309472 means 1,625,309,472 seconds after the epoch, which is 3 July 2021, 10:51:12 UTC. Timestamps are useful because:

  • They’re a single number, so they’re easy to store, sort, and compare.
  • They don’t depend on timezones. The same moment has the same timestamp everywhere in the world.
  • The difference between two timestamps is the number of seconds between them.

In Python, a timestamp is usually a float. The part after the decimal point is the fraction of a second, so it can be accurate to microseconds. Timestamps ignore leap seconds: every day counts as exactly 86,400 seconds.

The image below shows the same moment written in different formats:

timestamp representation
timestamp representation

Get Current Timestamp

To get the current timestamp in Python, you can use any of these modules:

  • datetime: datetime.now().timestamp()
  • time: time.time()
  • calendar: calendar.timegm(time.gmtime())

Datetime to Timestamp

The timestamp() method of a datetime object returns the POSIX timestamp of that datetime as a float.

  • First, get the current date and time in Python using datetime.now().
  • Next, call its timestamp() method to get the Unix timestamp.

Example:

from datetime import datetime

dt = datetime.now()
ts = dt.timestamp()

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

Output:

Date and time is: 2026-12-01 12:10:39.846903
Timestamp is: 1796107239.846903
Whole seconds: 1796107239

Your output will show the time when you run the code. The timestamp is a float. Use int(ts) to drop the fraction of a second.

You can get the timestamp of any datetime, not only the current one:

from datetime import datetime, timezone

dt = datetime(2021, 7, 3, 10, 51, 12, tzinfo=timezone.utc)
print(dt.timestamp())

# the epoch itself has timestamp 0
print(datetime(1970, 1, 1, tzinfo=timezone.utc).timestamp())Code language: Python (python)

Output:

1625309472.0
0.0

Get Timestamp Using time Module

The time module‘s time() function returns the current time as seconds since the epoch, as a float. It’s the quickest way to get the current timestamp.

For more precision, time.time_ns() (Python 3.7+) returns the timestamp in nanoseconds as an integer.

import time

print("Timestamp:", time.time())
print("Timestamp (ns):", time.time_ns())Code language: Python (python)

Output:

Timestamp: 1796107239.8742185
Timestamp (ns): 1796107239874227274

Get Timestamp Using calendar Module

The calendar module’s timegm() function converts a UTC time tuple into a timestamp. It returns a whole number of seconds.

  • First, import the time and calendar modules.
  • Next, get the current UTC time as a tuple with time.gmtime().
  • Finally, pass it to calendar.timegm() to get the timestamp.

Example:

import calendar
import time

current_utc = time.gmtime()
ts = calendar.timegm(current_utc)
print("Current timestamp:", ts)

# timegm() also works for any UTC date
print(calendar.timegm((2021, 7, 3, 10, 51, 12)))Code language: Python (python)

Output:

Current timestamp: 1796107239
1625309472

calendar.timegm() treats the tuple as UTC. Its opposite, time.mktime(), treats a tuple as local time.

Convert Timestamp to Datetime (format)

Use the datetime.fromtimestamp() method to convert a timestamp back into a datetime object.

Syntax:

datetime.fromtimestamp(timestamp, tz=None)Code language: Python (python)
  • Without tz, it returns your computer’s local date and time as a naive datetime.
  • With tz=timezone.utc (or another timezone), it returns an aware datetime in that timezone.

Example:

from datetime import datetime, timezone

ts = 1617295943.17321

print("UTC:  ", datetime.fromtimestamp(ts, tz=timezone.utc))
print("Local:", datetime.fromtimestamp(ts))Code language: Python (python)

Output:

UTC:   2021-04-01 16:52:23.173210+00:00
Local: 2021-04-01 22:22:23.173210

The same timestamp gives different clock times: the first line is UTC, and the second is the local time of the computer that ran this example (India, UTC+05:30). Your local result depends on your timezone.

To get only the date, use date.fromtimestamp(ts) or call .date() on the result.

Convert Timestamp to String

To show a timestamp as readable text:

  • First, convert the timestamp to a datetime with fromtimestamp().
  • Next, format it with strftime() and the format codes you need.

Example:

from datetime import datetime, timezone

timestamp = 1625309472.357246
date_time = datetime.fromtimestamp(timestamp, tz=timezone.utc)

print("Result 1:", date_time.strftime("%d-%m-%Y, %H:%M:%S"))
print("Result 2:", date_time.strftime("%d %B, %Y"))
print("Result 3:", date_time.strftime("%I:%M:%S %p"))
print("ISO 8601:", date_time.isoformat())Code language: Python (python)

Output:

Result 1: 03-07-2021, 10:51:12
Result 2: 03 July, 2021
Result 3: 10:51:12 AM
ISO 8601: 2021-07-03T10:51:12.357246+00:00

Timestamps are often shared in ISO 8601 format, such as 2014-09-12T19:34:29Z. The T separates the date from the time, and Z means UTC (“zero” offset).

String to timestamp: To go the other way, parse the string with strptime() or fromisoformat(), then call timestamp():

from datetime import datetime

dt = datetime.fromisoformat("2014-09-12T19:34:29Z")
print(dt, "->", dt.timestamp())Code language: Python (python)

Output:

2014-09-12 19:34:29+00:00 -> 1410550469.0

Get Timestamp in Milliseconds

Many systems, including JavaScript and Java, use timestamps in milliseconds. Multiply the seconds by 1000 and convert to an integer:

import time
from datetime import datetime, timezone

# current timestamp in milliseconds
print(int(time.time() * 1000))
print(time.time_ns() // 1_000_000)

# a specific datetime in milliseconds
dt = datetime(2012, 2, 23, 9, 12, tzinfo=timezone.utc)
print(int(dt.timestamp() * 1000))Code language: Python (python)

Output:

1796107239947
1796107239947
1329988320000

time.time_ns() // 1_000_000 avoids the small rounding errors that a float can have.

Get The UTC timestamp

The result of timestamp() depends on whether the datetime is aware or naive:

  • If the datetime is aware (it has a tzinfo), timestamp() uses that timezone, and the result is always correct.
  • If the datetime is naive, Python assumes it’s in your computer’s local time. So the same code gives different timestamps on computers in different timezones.

If your naive datetime is actually in UTC, attach the UTC timezone with replace(tzinfo=timezone.utc) before calling timestamp().

Get timestamp from datetime with UTC timezone

from datetime import datetime, timezone

date_time = datetime.strptime("23.02.2021 09:12:00", '%d.%m.%Y %H:%M:%S')

utc_timestamp = date_time.replace(tzinfo=timezone.utc).timestamp()
print("UTC timestamp:", utc_timestamp)

local_timestamp = date_time.timestamp()   # treated as local time
print("Local timestamp:", local_timestamp)Code language: Python (python)

Output:

UTC timestamp: 1614071520.0
Local timestamp: 1614051720.0

The two results differ by 19,800 seconds (5 hours 30 minutes) because this example ran on a computer set to India time. On a computer set to UTC, they would be the same.

The current UTC timestamp is simply datetime.now(timezone.utc).timestamp(). It’s the same as time.time(), because a timestamp always counts from the epoch in UTC.

Timestamp from datetime with a Different Timezone

A datetime in any timezone can be converted to a timestamp, as long as it’s aware. You can make it aware with ZoneInfo, or parse a string that contains a UTC offset with %z.

Read: Working with timezone in Python.

from datetime import datetime
from zoneinfo import ZoneInfo

# from a string with an offset
dt1 = datetime.strptime("23/Feb/2012:09:15:26 +0900", '%d/%b/%Y:%H:%M:%S %z')
print("Datetime:", dt1)
print("Timestamp:", dt1.timestamp())

# from a ZoneInfo timezone: the same moment in New York
dt2 = datetime(2012, 2, 22, 19, 15, 26, tzinfo=ZoneInfo('America/New_York'))
print("Datetime:", dt2)
print("Timestamp:", dt2.timestamp())Code language: Python (python)

Output:

Datetime: 2012-02-23 09:15:26+09:00
Timestamp: 1329956126.0
Datetime: 2012-02-22 19:15:26-05:00
Timestamp: 1329956126.0

Both datetimes describe the same moment (9:15 in Tokyo’s offset equals 19:15 the previous evening in New York), so they have the same timestamp.

Convert an Integer Timestamp to Datetime

An integer timestamp works with fromtimestamp() just like a float. If the timestamp is in milliseconds, divide it by 1000 first:

from datetime import datetime, timezone

ts_seconds = 1329988320
ts_millis = 1329988320000

print(datetime.fromtimestamp(ts_seconds, tz=timezone.utc))
print(datetime.fromtimestamp(ts_millis / 1000, tz=timezone.utc))Code language: Python (python)

Output:

2012-02-23 09:12:00+00:00
2012-02-23 09:12:00+00:00

Tip: A timestamp in seconds for a recent date has 10 digits, and one in milliseconds has 13 digits. If fromtimestamp() raises an error such as ValueError: year 44115 is out of range, you probably passed milliseconds instead of seconds.

Note: Older code often uses datetime.utcfromtimestamp(ts). It’s deprecated since Python 3.12 because it returns a naive datetime that is easy to mistake for local time. Use datetime.fromtimestamp(ts, tz=timezone.utc) instead.

Calculate Time Difference Using Timestamps

Because a timestamp is a number of seconds, subtracting two timestamps gives the number of seconds between them:

from datetime import datetime, timezone

start = datetime(2021, 7, 3, 9, 0, tzinfo=timezone.utc).timestamp()
end = datetime(2021, 7, 4, 11, 30, tzinfo=timezone.utc).timestamp()

seconds = end - start
print("Seconds:", seconds)
print("Hours:", seconds / 3600)Code language: Python (python)

Output:

Seconds: 95400.0
Hours: 26.5

For durations in days, hours, and minutes, you can also subtract the datetime objects directly to get a timedelta.

Summary

TaskUse
Current timestamptime.time() or datetime.now().timestamp()
Current timestamp in millisecondstime.time_ns() // 1_000_000
Datetime to timestampdt.timestamp() (make dt aware for reliable results)
Timestamp to UTC datetimedatetime.fromtimestamp(ts, tz=timezone.utc)
Timestamp to local datetimedatetime.fromtimestamp(ts)
Timestamp to stringdatetime.fromtimestamp(ts, tz=timezone.utc).strftime(fmt)
UTC time tuple to timestampcalendar.timegm(t)

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
Java Exercises
C# 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
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 a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

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
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

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