Demo entry 6229557

Python timezone


Submitted by py_tz on Oct 13, 2016 at 09:49
Language: Python. Code size: 1.0 kB.

import time
from datetime import datetime

from django.utils.timezone import get_default_timezone

def dt2ts(datetime):
    return time.mktime(datetime.timetuple())

def ts2dt(timestamp):
    return datetime.fromtimestamp(timestamp, tz=get_default_timezone())

class DateTimeUtilsTestCase(TestCase):

    def test_ts2dt2ts(self):
        self.assertEqual(dt2ts(ts2dt(1476301681)), 1476301681)
        test_dt = datetime.datetime(year=2016, month=10, day=13, hour=9, minute=12, second=15, microsecond=0,

    def test_dt2ts2dt(self):
        self.assertEqual(ts2dt(dt2ts(test_dt)), test_dt,
                         msg='{} not equal {}'.format(ts2dt(dt2ts(test_dt)), test_dt))

# AssertionError: datet[26 chars] 9, 12, 15, tzinfo=<DstTzInfo 'Europe/Moscow' MSK+3:00:00 STD>) != datet[26 chars] 9, 12, 15, tzinfo=<DstTzInfo 'Europe/Moscow' LMT+2:30:00 STD>) : 2016-10-13 09:12:15+03:00 not equal 2016-10-13 09:12:15+02:30

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).