- How to get Timestamp in Python?
- Table of contents
- What is timestamp in Python?
- Ways to get current timestamp in Python
- Using calendar Module
- Syntax:
- Example:
- Output:
- Using time Module
- Syntax:
- Example:
- Output:
- Using datetime Module
- Syntax:
- Example:
- Output:
- Convert timestamp to date and time
- Syntax:
- Example:
- Output:
- Example1:
- Output:
- Example2:
- Output:
- Example3:
- Output:
- Closing Thoughts
- How to Get Current Time in Python? (All Examples)
- How to get Current Time in Python?
- Printing the Current Timestamp
- Current Time in Milliseconds
- How to get Current Time from the Internet?
- Conclusion
How to get Timestamp in Python?
In this short tutorial, we look at what is Timestamp in Python. We will understand the different ways to get the timestamp and convert timestamp to date and time.
Table of contents
What is timestamp in Python?
Timestamp is the date and time of occurrence of an event. In Python we can get the timestamp of an event to an accuracy of milliseconds. The timestamp format in Python returns the time elapsed from the epoch time which is set to 00:00:00 UTC for 1 January 1970.
Ways to get current timestamp in Python
There are three modules in Python, using which, we can get the timestamp. These are-
Let us see these methods one by one.
Using calendar Module
In Python, the calendar module provides various functions related to calendar. In this module, the function calendar.timegm() returns the current time in the timestamp format. Let us understand this through the following example.
Syntax:
Example:
import calendar import time current_GMT = time.gmtime() time_stamp = calendar.timegm(current_GMT) print("Current timestamp:", time_stamp)
Output:
Current timestamp: 1647838478
Here, we import the modules calendar and time. We then get the current GMT time in a tuple format and save that to the current_GMT field. The calendar.timegm(current_GMT) function gets the current timestamp. Finally, we print the value saved in the current_GMT field.
In this way, we can use the calendar module in Python to get the timestamp. Now let us look at the time module method.
Using time Module
The time() function of the time module in Python gives the current time in timestamp format. To see how this works, let us go through the example below.
Syntax:
Example:
import time time_stamp = time.time() print("Timestamp:", time_stamp)
Output:
Current timestamp: 1625309785.482347
In this case, we first import the time module in Python. We create a field time_stamp to save the output of the time.time() function which gives the current timestamp. This output time is in seconds as the epoch is a floating-point number.
Using datetime Module
In Python, the datetime module provides classes for manipulating dates and times. Using this module’s datetime() function, we can get the current timestamp. Below is the syntax and an example to understand this better.
Syntax:
Example:
import datetime; current_time = datetime.datetime.now() time_stamp = current_time.timestamp() print("timestamp:-", time_stamp)
Output:
Current timestamp: 1625309785.482347
In the example above, we have first imported the datetime module. We then store the current time in the variable current_time using the function datetime.datetime.now(). We then obtain the timestamp using the function current_time.timestamp() and print the final value.
Convert timestamp to date and time
As we have seen in the time, datetime and calendar module methods to return the current timestamp, the output is a floating number which cannot be understood on reading. This, we need to convert this to a date and time format, in order to make it easy to understand for us. This can be done with the fromtimestamp() method.
Syntax:
datetime.fromtimestamp(timestamp, tz=None)
Example:
from datetime import datetime time_stamp = 1617295943.17321 date_time = datetime.fromtimestamp(time_stamp) print("The date and time is:", date_time)
Output:
The date and time is: 2021-04-01 16:52:23.173210
Thus, the time corresponding to the epoch timeline, as returned in the time and calendar module methods we saw, is converted into an understandable format of date and time. In the function datetime.fromtimestamp(timestamp, tz=None), t stands for Time and z stands for the Zero timezone which represents the offset from the coordinated universal time(UTC). We set the tz=none as we don’t want the timestamp to converted the platform’s local date and time, and the returned datetime object to be naive.
We can convert this output to a string as well for more convenience. Let us look at the method to do this.
Example1:
from datetime import datetime timestamp = 1625309472.357246 date_time = datetime.fromtimestamp(timestamp) str_date_time = date_time.strftime("%d-%m-%Y, %H:%M:%S") print("Current timestamp", str_date_time)
Output:
Current timestamp 03-07-2021, 10:51:12
In the above example, we have converted the timestamp from floating numbers to a DD-MM-YY, HH:MM:SS format. This is done using the date_time.strftime() function and specifying the format.
Example2:
from datetime import datetime timestamp = 1625309472.357246 date_time = datetime.fromtimestamp(timestamp) str_date = date_time.strftime("%d %B, %Y") print("Current timestamp", str_date)
Output:
Current timestamp 03 July, 2021
Here, the format to which we convert the timestamp is DD Month_name, YYYY. The steps to convert the timestamp remains the same, we have just changed the format to display it.
Example3:
from datetime import datetime timestamp = 1625309472.357246 date_time = datetime.fromtimestamp(timestamp) str_time = date_time.strftime("%I%p %M:%S") print("Current timestamp", str_time)
Output:
Current timestamp 10AM 51:12
The example above returns the timestamp in the format HH:AM/PM MM:SS. Thus, the current timestamp can be converted to different formats as per our requirement.
Closing Thoughts
In this tutorial, we understood what timestamp is. We saw how to get a current timestamp in Python and convert it to different date and time formats. Among the two methods we have seen, the time module method is an easy way to get the timestamp. However, it is important to convert the timestamp to a date and time format to understand the floating value output.
How to Get Current Time in Python? (All Examples)
Python has grown in popularity as a programming language for a wide range of jobs, but working with time is one job in which it excels. In this article, we’ll look at some of the ways to get the current time in Python.
How to get Current Time in Python?
Here we will learn how to discern current time attributes such as the year, minutes, and seconds. We will also look into printing choices with time formats, how computers represent time, and how to cope with time zones.
Python includes a datetime.now() method that is used to get the current time. It is a part of the built-in datetime module that simplifies dealing with dates and times. This will print the current date and time in the style YYYY-MM-DD HH:MM:SS.sssss.
Here is the syntax for this purpose:
import datetime current_time = datetime.datetime.now() print(current_time)
In the above example, we have imported the datetime class and then we used the now() function to get a datetime object containing the current date and time.
If you want to print the current time in a specific format, you can use the strftime() function. The below code with print time in the format HH:MM:SS.
import datetime current_time = datetime.datetime.now() formatted_time = current_time.strftime('%H:%M:%S') print(formatted_time)
Printing the Current Timestamp
We can use the time module’s time() function to print the current timestamp in Python. It will get the number of seconds (as a floating-point number) that have passed since January 1, 1970. This is the Unix approach as well.
import time current_timestamp = time.time() print(current_timestamp)
We first call the time() function from the time module, which returns the current timestamp. We then print the current_timestamp variable using the print() function.
Current Time in Milliseconds
If you need the current time with millisecond precision, you can combine the datetime.now() function with the strftime() function.
import datetime current_time = datetime.datetime.now() formatted_time = current_time.strftime('%Y-%m-%d %H:%M:%S.%f') print(formatted_time[:-3])
How to get Current Time from the Internet?
Sometimes, we need to get the time from the internet to be more specific. You can use the requests module to make a call to a time API to get the current time from the internet in Python.
The following code, for example, utilizes the World Time API to obtain the current time in America:
import requests response = requests.get('http://worldtimeapi.org/api/timezone/America/New_York') json_response = response.json() if 'utc_datetime' in json_response: current_time = json_response['utc_datetime'] print(current_time) else: print("No UTC datetime found in response")
This code will check if the «utc_datetime» key is present in the response, and if so, it will print out its value. Otherwise, it will print out a message saying that no UTC datetime was found in the response.
Another method for this is using the pytz library. You can use the datetime module to create a datetime object for the current time and then use the pytz module to convert this object to a specific time zone.
from datetime import datetime import pytz # Get the timezone object for London timez= pytz.timezone('Europe/London') datetime_London = datetime.now(timez) print(datetime_London)
The pytz is a third-party module that helps with time zones. It has an accurate database of time zones, as well as functions for converting between different time zones. To use pytz, you must first install it by running pip install pytz in your command prompt or terminal.
Conclusion
We now covered everything with getting current time in Python, which is very simple with the datetime module. Happy Learning 🙂