0

I am running this code to get timestamp from string But it giving wrong value for some particular value.

import datetime
import time
print(datetime.datetime.fromtimestamp(time.mktime(time.strptime("20170312025709", "%Y%m%d%H%M%S"))))

It is supposed to return "2017-03-12 02:57:09"## but it giving "2017-03-12 03:57:09"

what could be the reason. I am using python3.

Masudul Hasan
  • 137
  • 2
  • 17
  • What's your locale? I'm in Eastern Standard Time and it prints `2017-03-12 01:57:09` for me. – Mark Moretto May 08 '19 at 00:59
  • Off by one hour during summertime? That's where I'd start looking for the problem. – Grismar May 08 '19 at 01:07
  • https://docs.python.org/3/library/datetime.html#datetime.datetime.fromtimestamp and https://docs.python.org/3/library/time.html#time.mktime The answer is almost certainly in one of those. That said, why on Earth are you not just using [`datetime.strptime`](https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime) directly instead of running it through all those extra methods? – jpmc26 May 08 '19 at 04:24

2 Answers2

0

Your code works fine on my computer (GMT+8)

Results:

>>> import datetime
>>> import time
>>> print(datetime.datetime.fromtimestamp(time.mktime(time.strptime("20170312025709", "%Y%m%d%H%M%S"))))

2017-03-12 02:57:09

You might want to check your local time. Or something to do with daylight Saving time.

N. Arunoprayoch
  • 922
  • 12
  • 20
0

This is a trick question. daylight savings 2017.

import datetime
import time

for hour in range(25):
    time_str = "20170312" + str(hour).zfill(2) + "5709"
    print(
        datetime.datetime.fromtimestamp(
            time.mktime(time.strptime(time_str, "%Y%m%d%H%M%S"))))

Run this and you'll see an error at the end (there were only 23 hours on that day in your default system timezone).

soundstripe
  • 1,454
  • 11
  • 19