Unix Timestamp & Date Time Guide

Code Examples In Python


Introduction

Working with dates and times is a critical part of many programming tasks, such as scheduling events, logging activities, or performing time-based calculations.
Python provides a rich set of libraries and tools to handle date, time, Unix timestamps, and timezones effectively.
Python’s datetime module, part of the standard library, is the cornerstone for handling date and time.
It allows you to create, manipulate, and format dates and times with precision and flexibility. Additionally, Python offers tools to work with Unix timestamps—integer representations of time since the Unix epoch (January 1, 1970, UTC)—and to handle timezones for global applications.


Get Current Time

In Python, obtaining the current time is a fundamental operation used in a variety of applications.
Python provides a range of tools and libraries to make this task simple and flexible, catering to different requirements like working with local time, UTC, or timezone-aware timestamps.

Method:

1datetime.now()

Example:

1from datetime import datetime
2
3# Get the current date and time
4now = datetime.now()
5
6# Print the current time
7print("Current Time:", now)

Result:

1Current Time: 2024-11-01 21:09:09.174616

Get Unix Timestamp

Unix timestamps, representing the number of seconds elapsed since the Unix epoch (January 1, 1970, at 00:00:00 UTC), are a standard way of working with time in programming.
Python’s time module provides a simple and efficient method, time.time(), to get the current Unix timestamp.

Method:

1# Return the current time in seconds since the Epoch
2time.time()
3
4# Return POSIX timestamp as float.
5datetime.timestamp()

Example:

1import time
2from datetime import datetime
3
4# Get the current Unix timestamp
5unix_timestamp = int(time.time())
6
7# Print the Unix timestamp
8print("Current Unix timestamp:", unix_timestamp)
9
10unix_timestamp_float = time.time()
11print("Current Unix timestamp (with fractions):", unix_timestamp_float)
12
13# Get the current Unix timestamp
14unix_timestamp = int(datetime.now().timestamp())
15
16# Print the Unix timestamp
17print("Current Unix timestamp using timestamp():", unix_timestamp)

Result:

1Current Unix timestamp: 1733059209
2Current Unix timestamp (with fractions): 1733059209.0866532
3Current Unix timestamp using timestamp(): 1733059209

Construct New Time

Creating new date and time objects is a fundamental task in Python, especially when you need to represent specific points in time or perform time-related operations.
Python’s datetime module provides robust tools to construct datetime objects with precision and flexibility.

Method:

1# All arguments are optional.
2datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
3
4# The year, month and day arguments are required
5datetime.date(year, month, day)
6datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

Example:

1from datetime import time,date, datetime
2
3# Create using time()
4new_time = time(hour=10, minute=30, second=45)
5
6# Print the object
7print("New time:", new_time)
8
9# Create using date()
10new_date = date(year=2024, month=7, day=15)
11
12# Print the object
13print("New date:", new_date)
14
15# Create using datetime()
16new_date_time = datetime(year=2024, month=7, day=15, hour=11, minute=30, second=45)
17
18# Print the object
19print("New date time:", new_date_time)

Result:

1New time: 10:30:45
2New date: 2024-07-15
3New date time: 2024-07-15 11:30:45

Convert Unix timestamp to Readable Date Time

Unix timestamps, representing the number of seconds since the Unix epoch (January 1, 1970, at 00:00:00 UTC), are commonly used in programming for their simplicity and efficiency.
However, they are not human-readable, making it necessary to convert them into a readable date and time format for display, logging, or reporting purposes
Python provides powerful tools for converting Unix timestamps into human-readable datetime objects. These tools allow for precise control over formatting and timezone handling, making it easy to adapt the output for various applications.

Method:

1# Return the local date corresponding to the POSIX timestamp
2date.fromtimestamp(timestamp)
3
4# Return the local date and time corresponding to the POSIX timestamp
5datetime.fromtimestamp(timestamp, tz=None)
6
7# Return a string representing the date and time
8datetime.strftime(format)

Example:

1from datetime import date, datetime
2
3# Unix timestamp
4unix_timestamp = 1731029209
5
6# Convert to a date object
7converted_date = date.fromtimestamp(unix_timestamp)
8
9# Print the result
10print("Date:", converted_date)
11
12converted_datetime = datetime.fromtimestamp(unix_timestamp, tz=None)
13
14# Print the converted_datetime
15print("Date and Time:", converted_datetime)
16
17# converted_datetime in string format
18print("Date and Time in String:", converted_datetime.strftime("%Y-%m-%d %H:%M:%S"))

Result:

1Date: 2024-11-08
2Date and Time: 2024-11-08 09:26:49
3Date and Time in String: 2024-11-08 09:26:49

Convert Date Time to Unix timestamp

Converting a datetime object to a Unix timestamp is a common operation in Python, especially when working with systems or APIs that use timestamps as a standard format for representing time
Python provides straightforward methods to perform this conversion using the datetime module

Method:

1# Return POSIX timestamp corresponding to the datetime instance
2datetime.timestamp()

Example:

1from datetime import datetime
2
3# Readable date and time string
4readable_datetime = "2023-12-01 15:30:45"
5
6# Convert the string to a datetime object
7dt_object = datetime.strptime(readable_datetime, "%Y-%m-%d %H:%M:%S")
8
9# Convert the datetime object to a Unix timestamp
10unix_timestamp = dt_object.timestamp()
11
12# Print the result
13print("Unix timestamp:", unix_timestamp)

Result:

1Unix timestamp: 1701415845.0

Change Time Zone

Timezones play a critical role in applications that work with global users or time-sensitive data across different regions.
Python provides robust support for handling timezones through built-in libraries and additional tools like pytz and the zoneinfo module (introduced in Python 3.9). These tools allow you to work with timezone-aware datetime objects, convert times between timezones, and manage daylight saving time transitions seamlessly
By leveraging Python’s timedelta class, you can easily add or subtract days, hours, minutes, seconds, or even microseconds from a datetime object

Method:

1# need to install pytz by running "pip install pytz"
2# link: https://pypi.org/project/pytz/
3pytz.timezone()

Example:

1from datetime import datetime
2import pytz
3
4# Current time in UTC
5utc_now = datetime.now(pytz.utc)
6print("Current UTC time:", utc_now)
7
8# Convert to a specific time zone (e.g., US/Eastern)
9eastern = pytz.timezone("US/Eastern")
10eastern_time = utc_now.astimezone(eastern)
11print("Eastern time:", eastern_time)
12
13# Convert to another time zone (e.g., Asia/Kolkata)
14kolkata = pytz.timezone("Asia/Kolkata")
15kolkata_time = utc_now.astimezone(kolkata)
16print("Kolkata time:", kolkata_time)

Result:

1Current UTC time: 2024-10-03 13:45:26.695673+00:00
2Eastern time: 2024-10-03 08:45:26.695673-05:00
3Kolkata time: 2024-10-03 19:15:26.695673+05:30

Time Addition and Subtraction

Manipulating dates and times is a common requirement in many applications.
Python’s datetime module provides powerful tools to perform arithmetic operations on date and time objects, allowing for seamless addition and subtraction of time intervals.

Method:

1# All arguments are optional and default to 0.
2# Arguments may be integers or floats, and may be positive or negative
3datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Example:

1from datetime import datetime, timedelta
2
3now = datetime.now()
4print("Current datetime:", now)
5
6# Add 10 days
7future_date = now + timedelta(days=10)
8print("Future date (10 days ahead):", future_date)
9
10# Minus 2 hours
11future_time = now - timedelta(hours=2)
12print("Future time (2 hours ago):", future_time)
13
14# Calc time difference
15start_date = datetime(2023, 12, 1, 10, 0, 0)
16end_date = datetime(2023, 12, 3, 15, 30, 0)
17
18# Subtract the two dates
19difference = end_date - start_date
20print("Difference:", difference)
21
22# Access the total number of days, seconds, or hours
23print("Days:", difference.days)
24print("Seconds:", difference.seconds)  # Remaining seconds after days
25print("Total seconds:", difference.total_seconds())  # Full duration in seconds

Result:

1Current datetime: 2024-12-03 22:01:34.852455
2Future date (10 days ahead): 2024-12-13 22:01:34.852455
3Future time (2 hours ago): 2024-12-03 20:01:34.852455
4Difference: 2 days, 5:30:00
5Days: 2
6Seconds: 19800
7Total seconds: 192600.0

Pause or sleep for a specific time

Pausing or delaying the execution of a program is a common requirement in various applications, such as implementing retries, creating animations, scheduling tasks, or rate-limiting requests.
Python provides a simple and effective way to pause execution using the time.sleep() function.

Method:

1time.sleep()

Example:

1import time
2
3print("Start")
4
5# Sleep for 1 second
6time.sleep(1)
7
8print("End")

Result:

1Start
2End