viernes, 16 de marzo de 2018

How To Get Current Timestamp In Python


There is multiple ways how to get current timestamp in Python. If you want to get timestamp in Python, you may use functions from modules timedatetime, or calendar.

Using module time

Module time is providing various time related functions. One of them is time which return number of seconds since the epoch.

import time;
ts = time.time()
print(ts)
# 1521068985.78  

Using module datetime

Module datetime provides classes for manipulating date and time in more object oriented way. One of them is datetime.datetime.now which return number of seconds since the epoch.

import datetime;
ts = datetime.datetime.now().timestamp()
print(ts)
# 1521068985.78

Using module calendar

Another way how to get current timestamp is to combine multiple functions from multiple modules. Python provides also calendar module. In this case we will use function calendar.timegm to convert tuple representing current time.

import calendar;
import time;
ts = calendar.timegm(time.gmtime())
print(ts)
# 1521068985
Now, when you know how to get current timestamp, you may be interested in how to convert timestamp to human readable form.

No hay comentarios:

Publicar un comentario