- Timestamp In Python
- 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
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
- How to convert a datetime object to seconds?
- Date in Python
- Convert Datetime Object to Seconds
- Example: The total_seconds() Method
- Example: Use timestamp() method
- Example: Use calender.timegm() method
- Conclusion
Timestamp In Python
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
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.
Get Current Timestamp
To get the current timestamp in Python, use any of the following three modules.
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
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)
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.
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
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.
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.
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.
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.
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)
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.
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.
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)
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.
import datetime timestamp_int = 1329988320000 date = datetime.datetime.utcfromtimestamp(timestamp_int / 1e3) print("Corresponding date for the integer timestamp is::", date)
Corresponding date for the integer timestamp is:: 2012-02-23 09:12:00
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
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
How to convert a datetime object to seconds?
In this article, we will learn to convert datetime object to seconds in Python. We will use some built-in modules available and some custom codes as well to see them working. Let’s first have a quick look over what are dates in Python.
Date in Python
In Python, we can work on Date functions by importing a built-in module datetime available in Python. We have date objects to work with dates. This datetime module contains dates in the form of year, month, day, hour, minute, second, and microsecond. The datetime module has many methods to return information about the date object. It requires date, month, and year values to compute the function. Date and time functions are compared like mathematical expressions between various numbers.
Convert Datetime Object to Seconds
In Python, the date and time module provides various functions for the manipulation of dates. We can also convert a datetime object into seconds by applying mathematical operations. For this conversion, datetime module provides total_seconds method, calender method and timestamp method to convert a datetime object to seconds. The starting date is usually specified in UTC, so for proper results the datetime you feed into this formula should be in UTC as well. If your datetime isn’t in UTC already, you will need to convert it before you use it.
Example: The total_seconds() Method
1. datetime.strptime() formats the input timestamp into hh:mm:ss.
2. datetime.datetime() takes a year, month, day as arguments to create datetime object.
3. datetime.total_seconds() returns the total number of seconds.
The below example takes the time string into the acceptable format of hh:mm:ss. Python provides an operation on datetime to compute the difference between two dates. It finds the difference between the initial datetime object and the datetime object created from the time string. The value returned is a timedelta object from which we can use the function total_seconds() to get the value in seconds.
import datetime time = "01:01:09" date_time = datetime.datetime.strptime(time, "%H:%M:%S") a_timedelta = date_time - datetime.datetime(1900, 1, 1) seconds = a_timedelta.total_seconds() print(seconds)
Example: Use timestamp() method
Python 3 provides datetime.timestamp() method to easily convert the datetime object to seconds. This method will only be useful if you need the number of seconds from 1970-01-01 UTC. It returns a float value representing even fractions of a second. It is assumed that the datetime object represents the local time, i.e. it will be the number of seconds from the current time at your location to 1970-01-01 UTC.
from datetime import datetime #get current date dt = datetime.today() seconds = dt.timestamp() print(seconds)
Example: Use calender.timegm() method
Python 3 provides a standard library called calendar which has calendar.timegm() method to easily convert the datetime object to seconds. This method converts a datetime to seconds since Epoch i.e. 1970-01-01 UTC. As the above timestamp() method returns a float value, this method strips off the fractions of a second.
from datetime import datetime #get current date dt = datetime.today() seconds = dt.timestamp() print(seconds)
Conclusion
In this article, we learned to convert a datetime object into seconds format by using datetime module. We discussed the working of datetime functions using different code snippets.