Python Timestamp Functions

Soumya Agarwal
By
Soumya Agarwal
I'm a BTech graduate from IIITM Gwalior. I have been actively working with large MNCs like ZS and Amazon. My development skills include Android and Python...
7 Min Read

In Python, a timestamp is like a timestamp! It’s a number that tells you when something happened. This guide will help you get comfortable with timestamps in Python. We’ll talk about how to make them, change them, and why they’re useful.

Getting Started with Timestamp in Python

A timestamp is just a way of saying, “Hey, this happened at this exact moment.” It’s like marking time from a certain starting point. For us, that starting point is often January 1, 1970. Computers use timestamps a lot to keep track of when things occur.

Get Timestamps in Python

In Python, getting timestamps involves fetching the current time or converting existing time into timestamp format. Let’s explore different ways to get it:

Also Read: Python Get the Current Timestamp

Using the time Module

The time module is like your timekeeping buddy. It helps you figure out what time it is right now.

import time as tm

timestamp = tm.time()
print("Right Now:", timestamp)

Using the datetime Module

The datetime module is like the fancier version of time. It also helps you know what time it is but in a more human-friendly way.

from datetime import datetime as dt

timestamp = dt.now().timestamp()
print("Current Time:", timestamp)

Using timeit Module

The timeit module is handy for measuring the execution time of code snippets. While not directly for timestamp retrieval, it provides a way to gauge the time taken for a specific operation.

import timeit

start_time = timeit.default_timer()

# Your code or operation here

end_time = timeit.default_timer()
elapsed_time = end_time - start_time
print("Elapsed Time:", elapsed_time)

By measuring the time taken for a code block, you indirectly obtain a sense of time duration.

Using PYTZ for Timezone-Aware Timestamps

When working with timestamps in different time zones, the pytz library is useful. It allows you to create timezone-aware datetime objects and extract timestamps.

from datetime import datetime as dt
import pytz

timezone = pytz.timezone('America/New_York')
aware_time = dt.now(timezone)

timestamp = aware_time.timestamp()
print("Timestamp in New York:", timestamp)

Here, we use pytz.timezone to create a timezone object and then get the timestamp for the current time in that timezone.

Using Custom Functions

If you need a timestamp with higher precision, you can create a custom function using the time module.

import time as tm

def get_correct_tm():
    return tm.time_ns() / 1e9  # Nanoseconds to seconds

timestamp = get_correct_tm()
print("Correct Timestamp:", timestamp)

The time_ns() function returns the current time in nanoseconds, providing higher precision than seconds.

Convert Timestamps

In Python, you can convert timestamps between different representations using the datetime module. The datetime module provides a datetime class that can be used to represent dates and times. Here’s a guide on how to convert timestamps in Python:

From Timestamp to Regular Time

If you have a timestamp and want to know when it happened in regular words, you can do that too!

from datetime import datetime as dt

timestamp = tm.time()
regular_time = dt.fromtimestamp(timestamp)
print("Happened at:", regular_time)

From Regular Time to Timestamp

You can also go backward! If you have a normal time, you can turn it into a timestamp.

from datetime import datetime as dt

regular_time = dt.now()
timestamp = regular_time.timestamp()
print("Turned into Timestamp:", timestamp)

Timestamp Operations in Python

In Python, you can do operations on timestamps like addition or getting the time difference. Here are some common timestamp operations in Python:

Adding Time

You can even mess around with time. Wanna know what the date and time will be one day from now? Easy!

from datetime import datetime as dt, timedelta

timestamp = tm.time()
time_now = dt.fromtimestamp(timestamp)

one_day_later = (time_now + timedelta(days=1)).timestamp()
print("One Day Later:", one_day_later)

Making Time Look Pretty

Timestamps can look a bit clumsy. You can make them look nice and readable!

from datetime import datetime as dt

timestamp = tm.time()
time_now = dt.fromtimestamp(timestamp)

pretty_time = time_now.strftime("%Y-%m-%d %H:%M:%S")
print("Nice-looking Time:", pretty_time)

Get the Time Difference

Find the difference between two timestamps to measure the duration between two points in time.

from datetime import timedelta as td

tm1 = 1611064264  # Replace with your first timestamp
tm2 = 1611164264  # Replace with your second timestamp

time_diff = td(seconds=tm2 - tm1)
print(time_diff)

#Output 1 day, 3:46:40

Comparing Timestamps

Compare two timestamps to determine their chronological order (which one occurred earlier or later).

is_earlier = tm1 < tm2
is_later = tm1 > tm2

These operations enable you to work with time-related data in various use cases, such as calculating durations, making timestamps prettier, and also, comparing different points in time.

Smart Tips

Knowing Timezones

Sometimes, it’s crucial to know where something happened. Use the pytz library for that.

from datetime import datetime as dt
import pytz

utc_now = dt.now(pytz.utc)
print("Timestamp in UTC:", utc_now.timestamp())

No More Confusion with Decimals

Computers can be weird with numbers. To avoid confusion, use whole numbers for a really precise time.

Before You Leave

Getting the hang of Python timestamps is like having a superpower. It helps you understand when things are happening in your code. So, go ahead, play with timestamps, and make time work for you in your Python projects.

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Facebook) if you gained some knowledge from this tutorial.

Enjoy coding,
TechBeamers.

Share This Article
Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *