1

I want to convert timestamps to dates and truncate minute and seconds,then, convert it back to timestamps. I know I can do that with some mathematical algorithm like timestamps/60 or timestamps/3600, but I want to use Python provided functions. My code is like below. I tried two methods:

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)

In timestamp1 = time.mktime(day1), I got the error like:

TypeError: Tuple or struct_time argument required

In timestamp2 = time.mktime(day2), I got the error like:

OverflowError: mktime argument out of range

How can I convert it back to timestamps?

baldr
  • 2,891
  • 11
  • 43
  • 61
Zahra Aminolroaya
  • 520
  • 1
  • 5
  • 28

2 Answers2

2

Converting to string and back is very slow operation. I'd suggest to use that math algorithm anyway:

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

And that's it.

baldr
  • 2,891
  • 11
  • 43
  • 61
2

strftime("%Y-%m-%d %H") returns a string. If you want to go down this path, you should call strptime to turn it back into a time object:

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

I would recommend @baldr approach though...

Remi Smirra
  • 2,499
  • 1
  • 14
  • 15