Python get second-level timestamp and millisecond-level timestamp

created at 06-27-2021 views: 1

1. Get second-level timestamp, millisecond-level timestamp, and microsecond-level timestamp

import time
import datetime

t = time.time()

print (t)                       # Raw time data
print (int(t))                  # Timestamp in seconds
print (int(round(t * 1000)))    # Millisecond timestamp
print (int(round(t * 1000000))) # Microsecond timestamp


1499825149.257892    #Raw time data
1499825149           #Second-level timestamp, 10 bits
1499825149257        #Millisecond timestamp, 13 bits
1499825149257892     #Microsecond timestamp, 16 bits

2. Get the current date and time

dt    = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dt_ms = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') # Date and time with microseconds
print(dt)
print(dt_ms)


2018-09-06 21:54:46
2018-09-06 21:54:46.205213

3. Convert the date to a second-level timestamp

dt = '2018-01-01 10:40:30'
ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
print (ts)


1514774430

4. Convert the second-level timestamp to a date

ts = 1515774430
dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))
print(dt)


2018-01-13 00:27:10

5. Convert the time format to another time format

dt = '08/02/2019 01:00'
dt_new = datetime.datetime.strptime(dt, '%m/%d/%Y %H:%M').strftime('%Y-%m-%d %H:%M:%S')
print(dt_new)


2019-08-02 01:00:00

6. Time struct_time to transfer structure

ta_dt = time.strptime("2018-09-06 21:54:46", '%Y-%m-%d %H:%M:%S')  # Date and time to structure
ta_ms = time.localtime(1486188476) # Timestamp to structure, note that the timestamp requirement is int, the source is bit quantization
print(ta_dt)
print(ta_ms)


time.struct_time(tm_year=2018, tm_mon=9, tm_mday=6, tm_hour=21, tm_min=54, tm_sec=46, tm_wday=3, tm_yday=249, tm_isdst=-1)
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=7, tm_sec=56, tm_wday=5, tm_yday=35, tm_isdst=0)
Please log in to leave a comment.