Excel使用“ddddd.tttttt”格式对日期时间进行序列化,其中“d”部分是代表偏移量的整数,该偏移量是相对于参考日期(例如1899年12月31日)的。而“t”部分是介于0.0和1.0之间的分数,表示给定时间的一天中的部分(例如在12:00时是0.5,在18:00时是0.75等)。
我要求您上传一个包含样本数据的文件。“.xlsx”文件实际上是ZIP存档文件,其中包含XML序列化的工作表。这些是我从相关列中提取的日期。摘录如下:
38961.666666666628
38961.708333333292
38961.749999999956
当您尝试手动反序列化时,您会得到与Panda相同的日期时间。不幸的是,Excel存储时间的方式使得无法精确表示某些值,因此必须将它们舍入以便于显示。我不确定分析是否需要舍入后的数据。
以下是我用来测试反序列化的日期时间是否与Panda相同的脚本:
from datetime import date, datetime, time, timedelta
from urllib2 import urlopen
def deserialize(text):
tokens = text.split(".")
date_tok = tokens[0]
time_tok = tokens[1] if len(tokens) == 2 else "0"
d = date(1899, 12, 31) + timedelta(int(date_tok))
t = time(*helper(float("0." + time_tok), (24, 60, 60, 1000000)))
return datetime.combine(d, t)
def helper(factor, units):
result = list()
for unit in units:
value, factor = divmod(factor * unit, 1)
result.append(int(value))
return result
url = "https://gist.github.com/RaffaeleSgarro/877d7449bd19722b44cb/raw/" \
"45d5f0b339d4abf3359fe673fcd2976374ed61b8/dates.txt"
for line in urlopen(url):
print deserialize(line)