PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python DateTime » Timestamp In Python

Timestamp In Python

Updated on: December 5, 2021 | 1 Comment

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)

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.482347

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 1625310251

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)

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.173210

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)

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

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.0

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)

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)

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

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python DateTime

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 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted 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

All Python Topics

Python Basics Python Exercises Python Quizzes 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.

Explore Python

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

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

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, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com