The timestamp is a way of representing the date and time of a certain event. There are different methods you can use to get the timestamps in Python. We will be discussing all about Python Timestamp and various methods to get the current timestamp in Python in this article.
What is a Timestamp?
A timestamp is nothing but a representation of the moment a certain event has occurred. It is one of the most important metadata of any application stored to track time.
Here are a few examples of when timestamp is useful –
- The timestamp is used to track when the files are created, modified, or changed on a server.
- When you purchase something online, a timestamp can be used to store the time you have placed an order and to provide you with the tracking status.
- All your tweets are tagged with timestamps and are useful to display all your tweets in a certain order.
- OTT applications like Netflix, Amazon Prime, etc have a sort option to display new movies on the top and it is based on the movie release timestamp.
- Google ranks the pages based on their freshness and it is determined by the article’s published timestamp.
- HRMS applications store employee join dates in timestamps which can be used to wish or send gifts on a work anniversary.
- What is a Timestamp?
- Different timestamp formats with examples
- Different modules to work with Timestamp in Python
- Python get current Timestamp
- Python Timestamp to DateTime or Date:
- Python DateTime to Timestamp
- Convert String to Timestamp
- DateTime to String formatting
- Timestamp Practice Problems with Solutions in Python
- Frequently Asked Questions
Different timestamp formats with examples
Timestamps can be represented in different ways. Here are a few example timestamp formats:
- ISO 8601 format – This is the standard timestamp format widely used in applications. ISO 8601 format includes the date, time, and timezone and it looks like this – “2022-12-20T14:33:00Z”.
- Unix timestamp format – Unix timestamp is a number format and it represents the number of seconds elapsed from January 1st, 1970, 00:00:00 UTC. An example Unix timestamp is – 1671558472 (used to represent Tuesday, December 20, 2022, 5:47:52 PM UTC)
- Other human-readable formats – These are the generic format we use regularly to communicate the date and time. For example, 21st December 2022.
Which is the one most used?
Human-readable timestamp formats are simple and effective to communicate time with Humans. However, ISO 8601 and UNIX timestamps are usually used in computers and programming languages like Python.
Different modules to work with Timestamp in Python
There are several built-in and external libraries available in Python to work with Timestamps. Here are a few most used libraries for Python Timestamps.
1. time module
time module is one of the popular built-in libraries available in Python that provides numerous functions to work with timestamps. Most of the functions in this library internally utilise C library time functions.
You can import the time module in Python code as shown below.
import time
drawback with time module:
Not all the functions in the time()
library work as expected for dates before the epoch time (January 1, 1970) or far from the near future, typically after 2038.
2. datetime module
Another useful library to work with Python timestamps is datetime library. It provides different functions to manipulate dates and times. It works efficiently on extracting the output and manipulating the timestamps to different formats.
import datetime
Notes:
Unlike time
module, datetime
module allows you to work with a wider range of years as stated below.
import datetime
print(datetime.MINYEAR) #1
print(datetime.MAXYEAR) #9999
3. calendar module
calendar is an extensive library to work the standard Gregorian calendar. It has most of the functions to format, calculate and manipulate the dates, times, and days in the calendar.
calendar module provides a basic range of functions to work with calendars. Here is how you can import it to your python code.
import calendar
4. pandas module
We can also use the pandas module to get the current timestamp and various functions to work with Python timestamps and dates. You can create Timestamp object using pandas.Timestamp()
function.
import pandas
5. ZoneInfo module
Python’s ZoneInfo library gives you a lot of options to work with timestamps considering support for different timezones and daylight savings. You can import the zoneinfo with the below code.
import zoneinfo
6. dateutil library
The dateutil
library provides powerful extensions to the standard datetime
library in Python. Since it is not a part of the standard Python library, you need to install it separately using the below pip command.
pip3 install python-dateutil
Python get current Timestamp
1. Using time module
The time module provides time()
function that returns Unix timestamp in seconds.
- The
time()
function returns the Unix timestamp as a floating number time()
can come in handy to measure the time taken for any function or block of lines to execute.
Code Thread:
import time
current_time = time.time()
print(current_time)
Output:
1671561656.4659672
2. Use datetime module
Alternatively, In this method, we are using datetime
module for getting the current timestamp. We will be using below methods:
- now() function: returns
datetime
object representing the current date and time. - timestamp() function: returns the Unix time stamp in seconds based on the date and time that
datetime
object represents.
Notes
datetime.now()
function internally user time.time() function to get the current Unix timestamp.
Code Thread:
from datetime import datetime
current_timestamp = datetime.now().timestamp()
print(current_timestamp)
Output:
1671562343.647376
3. calendar module
In this method, we will use calendar and time libraries to get the current timestamp.
time.gmtime():
returns the current timestamp in time.struct_time format. time.struct_time uses 9 integers to represent a timestamp. Following are those 9 integers.- tm_year – stores year. ex: 2022
- tm_mon – for the month, from 1 to 12. ex: 12
- tm_mday – represents the day of the month – ex: 21
- tm_hour – for hours. ranges from 0 to 23.
- tm_min – for minutes, 0 to 59.
- tm_sec – for seconds, 0 to 61. yes, it’s 61, not 59. for accommodating the leap seconds.
- tm_wday – for the day of the week, ranges from 0 to 6.
- tm_yday – for the day of the year, from 1 to 366. Yet, it starts with 1, not with 0.
- tm_isdst – accepts [-1,0,1]. 1 for DST, 0 for no DST, and -1 for unknown.
calendar.timegm():
It takes time.struct_time as input, calculates the Unix timestamp from the above listed 9 integers, and returns it.
Code Thread:
import calendar
import time
current_timestamp = calendar.timegm(time.gmtime())
print(current_timestamp)
Output:
1671562743
4. Using Pandas timestamp
We can also use pandas library to get the current timestamp in Python.
Code Thread:
import pandas as pd
current_timestamp = pd.Timestamp.now().timestamp()
print(current_timestamp)
Output:
1671668985.031944
If you want to convert to any other DateTime format or human-readable timestamp format, check out the sections below.
Python Timestamp to DateTime or Date:
We can convert timestamp to datetime using datetime
and time
modules. In the following sections, we will explain each method in detail.
Method 1: Using datetime module
The datetime
library provides a lot of options to handle date and time in Python. One such function is, fromtimestamp()
which can be used to get datetime from the timestamp.
Function signature: def fromtimestamp(t, tz=None)
- t – Unix timestamp in seconds – required
- tz – Timezone – optional
Code Thread:
import time
from datetime import datetime
# get current time in secs using time modules time() function
time_stamp_in_sec = time.time()
# we are converting time stamp in secs to date time
date_time = datetime.fromtimestamp(time_stamp_in_sec)
print(date_time)
Output:
2022-12-21 01:18:08.753661
Code Thread for Timestamp to Date:
import time
time_stamp_in_sec = time.time()
# we are converting time stamp in secs to date time
date_time = datetime.fromtimestamp(time_stamp_in_sec)
# formatting datetime object, %Y for getting 4 digit year, %m to get month number[1-12], %d for day of the month
print(date_time.strftime('%Y-%m-%d))
Output:
2022-12-21
We have explained DateTime and time formatting using strftime()
in the later sections of this page, scroll down to the formatting section and understand more about strftime()
.
Method 2: Use time module
The ctime()
function from the time module, takes the number of seconds from the Unix epoch and converts it to a local time string, and returns it.
ctime() notes:
The ctime() function returns String, so it does not support any formatting.
Code Thread:
import time
time_stamp_in_sec = time.time()
res = time.ctime(time_stamp_in_sec)
print(res)
Output:
Thu Dec 22 00:47:55 2022
Method 3: Using time module
Code Thread:
time_stamp_in_sec = time.time()
res = time.localtime(time_stamp_in_sec)
print(time.strftime('%Y-%b-%d %I:%M:%S %p', res))
Output:
2022-Dec-22 01:21:48 AM
Code Thread for Timestamp to Date in Python:
time_stamp_in_sec = time.time()
res = time.localtime(time_stamp_in_sec)
print(time.strftime('%Y-%m-%d', res))
Output:
2022-12-22
Python DateTime to Timestamp
Similar to how we convert Timestamp to DateTime, There might be use cases where we need to convert Python DateTime to Timestamp. We can use calendar module to convert the DateTime format to Timestamp format.
Code Thread:
from datetime import datetime as dt
current_date_time = dt.now()
current_time_in_sec = current_date_time.timestamp()
print(int(current_time_in_sec))
Output:
1671567049
Code Thread for Date to Timestamp:
from datetime import datetime
date = datetime(2022, 12, 21)
print(date.timestamp())
Output:
1671561000.0
Convert String to Timestamp
You can convert a date string to a DateTime object using strptime()
function from datetime
module. Once you have the DateTime
object, we can use all the above methods to convert the DateTime
object to Unix Timestamp.
Example1:
from datetime import datetime as dt
# 1. converting string to DateTime Object
datetime_str = '2022-12-21 12:54:51'
date_time = dt.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
print('date_time:',date_time)
# 2. converting DateTime object to Timestamp
time_stamp = int(date_time.timestamp())
print('time_stamp:', time_stamp)
Output:
date_time: 2022-12-21 12:54:51
time_stamp: 1671607491
Example2:
from datetime import datetime as dt
# 1. converting string to DateTime Object
datetime_str = '21/12/2022 12:54:51'
date_time = dt.strptime(datetime_str, '%d/%m/%Y %H:%M:%S')
print('date_time:',date_time)
# 2. converting DateTime object to Timestamp
time_stamp = int(date_time.timestamp())
print('time_stamp:', time_stamp)
Output:
date_time: 2022-12-21 12:54:51
time_stamp: 1671607491
DateTime to String formatting
datetime
and time
libraries offer strftime()
function to get string different formats from datetime
and time
objects.
Following are the codes used for strftime()
formatting. All the codes are prepended with the %
symbol. For example: %Y, for 4 digit year.
Code | Used For |
Y | 4-digit years including the century. For example: 2022. |
y | 2-digit years without the century. For example: 22, 23, and 24. |
m | Month number from 1 to 12. |
b | Shorthand month names like Dec, Jan, Feb, etc. |
B | Full month names like December, January, February, etc. |
d | Day of the Month from 1 to 31. |
w | Day of the week from 0 to 6. |
a | Shorthand for weekdays like Mon, Tue, etc. |
A | Full weekdays like Monday, Tuesday, etc. |
H | Hours from 0 to 23. |
I | Hours from 1 to 12. |
p | For AM and PM. |
M | Minutes starting from 0 to 59. |
S | Seconds starting from 0 to 59. |
f | Microseconds in a 6-decimal number. |
Timestamp Practice Problems with Solutions in Python
Hope you have got the gist of Timestamps in Python. Let’s practice a few problems on Timestamps.
Below are a few practice problems whose solutions cover all the important timestamp-related libraries in Python. Try to answer them once you are done reading this page. If you need help you can find the solutions at the end of this page.
Timestamp Practice Problems – solutions:
Problem 1: Read FIFA world cup final date from the user in YYYY-MM-DD format and print on what weekday it happened.
Solution:
from datetime import datetime
# Used input() function to read input from the user
scheduled_date_str = input("When is the Qatar FIFA World Cup Final(YYYY-MM-DD)?")
print(scheduled_date_str)
# Used strptime() to parse string and return datetime object
scheduled_date_time = datetime.strptime(scheduled_date_str, "%Y-%m-%d")
print(scheduled_date_time)
# we used strftime() function and code A for getting full week day name
weekday = scheduled_date_time.strftime("%A")
print(weekday)
Output:
When is the Qatar FIFA World Cup Final(YYYY-MM-DD)?2022-12-18
2022-12-18
2022-12-18 00:00:00
Sunday
Problem 2: Let’s assume we are working for a SAAS company that offers a free trial of 15 days for its customers to test out and feel their product. We need to help the company by writing programs for the below cases.
A) Write a function that takes registration time as input and returns free trial end time
B) Write a function that takes the free trial end time as input and returns a string message as follows, “Your free trial ends in 3 days 5 hours 31 minutes.”
Solution A:
from datetime import timedelta
from datetime import datetime
def get_free_trial_end_time(registration_time):
return registration_time + timedelta(days=15)
print(get_free_trial_end_time(datetime.now()))
Output:
2023-01-06 02:16:09.329085
Solution B:
from datetime import timedelta
from datetime import datetime
def get_free_trial_end_time(t_registration_time):
return t_registration_time + timedelta(days=15)
def get_free_trial_end_message(t_free_trial_end_time):
remaining_time = t_free_trial_end_time - datetime.now()
remaining_secs = remaining_time.seconds
hours = remaining_secs // (60 * 60)
minutes = (remaining_secs % (60 * 60)) // 60
return "Your Free trial ends in "+ str(remaining_time.days) + " Days " + str(hours) + " Hours " + str(minutes) \
+ " Minutes."
registration_time = datetime(year=2022, month=12, day=20, hour=1, minute=51)
free_trial_end_time = get_free_trial_end_time(registration_time)
print(free_trial_end_time)
free_trial_message = get_free_trial_end_message(free_trial_end_time)
print(free_trial_message)
Output:
2023-01-04 01:51:00
Your Free trial ends in 12 Days 23 Hours 1 Minutes.
Frequently Asked Questions
-
What is timestamp() in Python?
A timestamp is a representation of the date and time of an event. It is one of the most used data to store the event time. In this guide, we have listed down different ways to get the current time in Python along with various modules that you can use to work with Python timestamps.
-
Are Timestamp and DateTime are same?
No. The timestamp is a generic term to represent the time. There are different formats of representation of Timestamps. Most people refer to Timestamp as Unix Timestamp (or epoch time lapsed).
For more insightful stories, follow codethreads.dev!!!
This is extremely helpful. All the code examples and explanations are on point. Thank you.