Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

Can not convert 13 digit UNIX timestamp in python

Still new to this. I have tried to convert a 13 digit timestamp to something that you can read but to no luck. What i am doing is sampling temperature data from a building automation system. This is the code that i am working with. I am missing something very simple. Can i get a poke in the right direction.

when_updated=driver.find_element_by_name("_lastUpdated")
timestamp=when_updated.get_attribute("value")
print("Timestamp:", timestamp)

nos=10  # Number of samples
freq=5  # Sampling frequency
print("
Temperature & timestamp, sampled every", freq, "seconds:")
while True:
     ts=driver.find_element_by_name("_lastUpdated").get_attribute("value")
     print("
Temperature: ", element.text, "read at:", ts)
     time.sleep(freq)


driver.switch_to_default_content()

OUTPUT

Temperature:

Timestamp: 0

Temperature & timestamp, sampled every 5 seconds:

Temperature:   read at: 0

Temperature:  21.0 oC read at: 1520912895599

Temperature:  21.0 oC read at: 1520912901432

Temperature:  21.0 oC read at: 1520912907070
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
#!python2

# Epoch time needs to be converted to a human readable format.
# Also, epoch time uses 10 digits, yours has 13, the last 3 are milliseconds

import datetime, time

epoch_time = 1520912901432

# truncate last 3 digits because they're milliseconds
epoch_time = str(epoch_time)[0: 10]

# print timestamp without milliseconds
print datetime.datetime.fromtimestamp(float(epoch_time)).strftime('%m/%d/%Y -- %H:%M:%S')
'''
03/12/2018 -- 21:48:21
'''

# %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %

# If you need milliseconds
epoch_time = 1520912901432

# get first 10 digits
leading = str(epoch_time)[0: 10]

# get last 3 digits
trailing = str(epoch_time)[-3:]

# print timestamp with milliseconds
print datetime.datetime.fromtimestamp(float(leading)).strftime('%m/%d/%Y -- %H:%M:%S.') + ('%s' % int(trailing))
'''
03/12/2018 -- 21:48:21.432
'''

Python 2 time module: https://docs.python.org/2/library/time.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...