我有一个字符串时间戳。我想将它转换为秒数,稍后我想将该秒数转换为时间戳。因此,为此,我先将字符串转换为时间戳,然后计算秒数。我再次将秒数转换为时间戳。
但转换后的时间戳与原始时间戳不匹配。我该如何解决这个问题?
我使用以下代码进行此转换:
import datetime
import pandas as pd
def string_to_datetime(string):
dv = [string]
dv_series = pd.Series(dv)
dv_to_datetime = pd.to_datetime(dv_series)
dv_to_datetime_list = list(dv_to_datetime)
return dv_to_datetime_list[0]
timestamp = ['2020-06-12T08:33:14']
timestamp = string_to_datetime(timestamp[0])
print('timestamp:')
print(timestamp)
timestamp_in_seconds = float((timestamp - datetime.datetime(1970, 1, 1)).total_seconds())
print('timestamp in seconds:')
print(timestamp_in_seconds)
print('Again converted to timestamp:')
print(datetime.datetime.fromtimestamp(timestamp_in_seconds))
上面代码的输出如下:
timestamp:
2020-06-12 08:33:14
timestamp in seconds:
1591950794.0
Again converted to timestamp:
2020-06-12 14:33:14
最佳答案
我有两个解决方案。也许对以后的人有帮助。
solution_1 = datetime.datetime.fromtimestamp(timestamp_in_seconds, tz=pytz.UTC)
solution_2 = datetime.datetime.utcfromtimestamp(timestamp_in_seconds)
在转换回原始时间戳的过程中,时区信息很重要。
关于python - 以秒为单位的转换时间戳值不会反转为 python 中的原始时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64308908/