Python Sample code for obtaining second timestamp and millisecond timestamp

  • 2021-11-01 04:02:06
  • OfStack

1. Get second timestamp, millisecond timestamp and microsecond timestamp


import time
import datetime
 
t = time.time()
 
print (t)                       # Original time data 
print (int(t))                  # Second timestamp 
print (int(round(t * 1000)))    # Millisecond timestamp 
print (int(round(t * 1000000))) # Microsecond timestamp 

1499825149.257892 # Original time data
1499825149 # second 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 time including microseconds, source   Bit quantization 
print(dt)
print(dt_ms)

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

3. Change the date to a second 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 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. Transition time struct_time


ta_dt = time.strptime("2018-09-06 21:54:46", '%Y-%m-%d %H:%M:%S')  # Date-time to structure  
ta_ms = time.localtime(1486188476) # Time stamp to structure, note that the time stamp requirement is int Source   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)

Related articles: