0

I made a simple functions which converts date to timestamp and timestamp to date. However, the problem is that it's not working if the timestamp is negative and the date is before and even on 1 January 1970. Can you please help me? I can't find any sources related to this. I can solve this problem with raw MySQL but I am using now with pyDAL so I have no choice but to use Python in calculating these convertion.

import datetime
import time


def date(timestamp):
    return datetime.datetime.utcfromtimestamp(int(timestamp)) \
        .strftime('%d %B %Y')


def timestamp(date):
    return int(time.mktime(
        datetime.datetime.strptime(date, '%d %B %Y').timetuple()))


print(date('0'))
# 01 January 1970

print(date('-839939'))
# OSError: [Errno 22] Invalid argument

print(timestamp('31 December 1969'))
# OverflowError: mktime argument out of range

print(timestamp('1 January 1970'))
# OverflowError: mktime argument out of range

print(timestamp('2 January 1970'))
# 57600
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 1
    None of these commands raise an exception for me. And the last one prints `82800`. – Graipher Mar 02 '18 at 16:36
  • 1
    @Graipher The last one might differ by our timezone. – Lydia Kamakaeha Mar 02 '18 at 16:38
  • @Graipher Ah, okay I see. I might change the time during conversion to GMT but what if the date is '21 December 1969' and the timestamp is '-1000000'? – Lydia Kamakaeha Mar 02 '18 at 16:42
  • Possible duplicate of [how to create datetime from a negative epoch in Python](https://stackoverflow.com/questions/17231711/how-to-create-datetime-from-a-negative-epoch-in-python) – alex Mar 02 '18 at 19:28

0 Answers0