Python timestamp: How to get the current Unix timestamp

In Python, time function in time module returns the current Unix timestamp.

import time

t = time.time()

print(t)
# 1600500102.835746

print(type(t))
# <class 'float'>

The value is float. If you want the integer timestamp, use int function.

import time

t_ = time.time()
t = int(t_)

print(t)
# 1600500421

time module has many functions including time and time_ns.

Unix timestamp to date object

time function returns the current (float) Unix timestamp. But how can we get a datetime object from it?

import datetime
import time

t_ = time.time()
t = int(t_)

print(t)
# 1600500607


d_ = datetime.datetime.utcfromtimestamp(t_)
d = datetime.datetime.utcfromtimestamp(t)

print(d_)
# 2020-09-19 07:30:07.688975

print(d)
# 2020-09-19 07:30:07

The code shows how to convert the unix time to datetime. datetime module has datetime class and this class has utcfromtimestamp function that converts timestamp to datetime.

utcfromtimestamp can convert both float timestamp and int timestamp.

Unix timestamp from datetime

time.time() is the easiest way to get the current timestamp, but we can get it from datetime module.

import datetime

t = datetime.datetime.utcnow().timestamp()

print(t)  # 1601250864.211776

utcnow returns the current datetime.datetime object.

import datetime

u = datetime.datetime.utcnow()

print(u)  # 2020-09-28 08:58:15.115063
print(type(u))  # <class 'datetime.datetime'>

t = u.timestamp()

print(t)  # 1601251095.115364
print(type(t))  # <class 'float'>

Nanosecond timestamp

import time

t = time.time()
t_ns = time.time_ns()

print(t)  # 1601283767.132791
print(t_ns)  # 1601283767132798000

time returns the float timestamp and time_ns returns the integer timestamp as nanoseconds. time_ns is supported from Python 3.7.

1 second is 1,000,000,000 nanoseconds.

Comments

Powered by Markdown