无法在python中将更改日期时间转换回timeStamp

时间:2016-01-20 12:51:04

标签: python datetime unix-timestamp

我想将timestamps转换为dates并截断minuteseconds,然后将其转换回timestamps。我知道我可以使用timestamps/60timestamps/3600这样的数学算法来做到这一点,但我想使用Python提供的函数。我的代码如下。我尝试了两种方法:

for timeStamp in lineTimeStamps:
    #first try 
    day1=datetime.datetime.\
        fromtimestamp(float(timeStamp)).strftime("%Y-%m-%d %H")
    timestamp1 = time.mktime(day1)
    #second try 
    day2=datetime.datetime.\
        fromtimestamp(float(timeStamp)).\
        replace( minute=0, second=0, microsecond=0).timetuple()
    timestamp2 = time.mktime(day2)

timestamp1 = time.mktime(day1)中,我收到了如下错误:

  

TypeError:需要Tuple或struct_time参数

timestamp2 = time.mktime(day2)中,我收到了如下错误:

  

OverflowError:mktime参数超出范围

如何将其转换回timestamps

2 个答案:

答案 0 :(得分:2)

转换为字符串并返回非常慢的操作。无论如何我建议使用那个数学算法:

# get integer and fractional parts of modulo division
i, f = divmod(timeStamp, 3600)
# i * 3600 is hour:0:0 time
timestamp1 = i * 3600

就是这样。

答案 1 :(得分:1)

strftime("%Y-%m-%d %H")返回一个字符串。 如果您想沿着这条路走下去,您应该致电strptime将其转回时间对象:

 day1=datetime.datetime.\
    fromtimestamp(float(timeStamp)).strftime("%Y-%m-%d %H")
 day1 = time.strptime(day1, "%Y-%m-%d %H")
 timestamp1 = time.mktime(day1)

我会推荐@baldr方法......