I want to convert a time(String) to unix timestamp, then convert it back to readable datetime, however, there are 7 hours different. What is the problem in my python code?
import datetime
#Convert a Datetime String to unix timestamp
def get_Timestamp_from_String(datetimeStr):
timestamp = int(datetime.datetime.strptime(datetimeStr, '%Y-%m-%d %H:%M:%S').timestamp())*1000
return timestamp
# Convert unix timestamp to DateTime
def get_Datetime_from_Timestamp(timestamp):
dt = pd.to_datetime(timestamp, unit='ms')
return dt
Test the datetime: "2016-04-01 01:10:04", however, if I convert it back, then I got the result: '2016-04-01 08:10:04', there are 7 hours different
timestamp = get_Timestamp_from_String("2016-04-01 01:10:04")
res = get_Datetime_from_Timestamp(timestamp)
print(res)
>>>Timestamp('2016-04-01 08:10:04')
What is the problem in my code?
I think you need to_datetime
twice, for ms divide by 10**6
:
datetimeStr = '2016-04-01 01:10:04'
timestamp = pd.to_datetime(datetimeStr).value //10**6
print (timestamp)
1459473004000
dt = pd.to_datetime(timestamp, unit='ms')
print (dt)
2016-04-01 01:10:04
For ns
, native format of timestamps in numpy
dividing is not necessary:
datetimeStr = '2016-04-01 01:10:04'
timestamp = pd.to_datetime(datetimeStr).value
print (timestamp)
1459473004000000000
dt = pd.to_datetime(timestamp, unit='ns')
print (dt)
2016-04-01 01:10:04
But if have timezone information:
datetimeStr = '2016-04-01 01:10:04-07:00'
timestamp = pd.to_datetime(datetimeStr).value //10**6
print (timestamp)
1459498204000
dt = pd.to_datetime(timestamp, unit='ms')
print (dt)
2016-04-01 08:10:04
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.