Python Epoch time- unix timestamp with example
This tutorial explains about Current Epoch Or unix timestamp in Python.
Epoch TIme is several seconds completed from 00:00:00 UTC on 1 January 1970 to the Current DateTime.
It contains a long number that represents seconds
How to print Current Epoch Timestamp in Python
Many ways we can get Unix timestamps in Python.
Listing out two ways.
- time library
- datetime module
The time
module provides utility functions on Date and time
time.time()
returns a floating number that indicates the number of seconds since Unix time. datetime.now().timestamp()
returns the time in epoch time
Here is an example
from time import time
from datetime import datetime
unixTime = time()
print(unixTime);
epochSeconds = datetime.now().timestamp()
print(epochSeconds);
Output:
1697082092.5620618
1697082092.562061
How to Convert Unix Timestamp into readable utc and local date and time
We can convert epoch time to date time format using datetime library
import datetime library into a cod
e
First get epoch timestamp using datetime.now().timestamp() that returns long value
datetime.fromtimestamp() takes epoch time
use
strftime
to format the time into date and time, You can customize the format as per readable format.This returns the time in the local timezone format
Here is an example
from datetime import datetime
epochSeconds = datetime.now().timestamp()
time = datetime.fromtimestamp(epochSeconds)
print(time.strftime('%Y-%m-%d')); # Year-Month-Date i.e 2023-10-12
print(time.strftime('%H-%M-%S')); # Hour-Minute-Seconds i.e 09-23-13
print(time); # 2023-10-12 09:23:13.264851
print(epochSeconds);
Output:
2023-10-12
09-23-13
2023-10-12 09:23:13.264851
Convert unix timestamp human readable UTC date and time The same code but pass timezone.utc
to fromtimestamp
function
from datetime import datetime,timezone
epochSeconds = datetime.now().timestamp()
time = datetime.fromtimestamp(
epochSeconds,timezone.utc)
print(time.strftime('%Y-%m-%d')); # Year-Month-Date
print(time.strftime('%H-%M-%S')); # Hour-Minute-Seconds
print(time);
print(datetime.now());
Output:
2023-10-12
03-59-46
2023-10-12 03:59:46.879310+00:00
How to parse Current Datetime into timestamp
datetime.now()
returns the current date and time information timestamp()
returns the current unix timestamp.
You can construct the datetime object by passing year, month, day, hour, minutes, and call timestamp(), outputs epoch seconds.
This is an example of calculating epoch time for a given date and time
from datetime import datetime
## Current Date and time
currentDate=datetime.now();
print(currentDate); # 2023-10-12 09:32:09.808697
epochSeconds = currentDate.timestamp();
print(epochSeconds); # 1697083329.808697
# Given Date and time
specificDate=datetime(2022,11,11,0,0)
print(specificDate); # 2022-11-11 00:00:00
epochSeconds1 = specificDate.timestamp();
print(epochSeconds1); # 1668105000.0