Skip to content

Commit

Permalink
Fix for epoch UTC bug
Browse files Browse the repository at this point in the history
  • Loading branch information
zachwill committed Jun 15, 2017
1 parent 0c98c36 commit f3a0ffa
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 8 deletions.
12 changes: 8 additions & 4 deletions moment/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 41,20 @@ def utcnow(cls):
@classmethod
def unix(cls, timestamp, utc=False):
"""Create a date from a Unix timestamp."""
# Which function are we using?
if utc:
fromtimestamp = datetime.utcfromtimestamp
func = datetime.utcfromtimestamp
else:
fromtimestamp = datetime.fromtimestamp
func = datetime.fromtimestamp
try:
# Seconds since epoch
date = fromtimestamp(timestamp)
date = func(timestamp)
except ValueError:
# Milliseconds since epoch
date = fromtimestamp(timestamp / 1000)
date = func(timestamp / 1000)
# Feel like it's crazy this isn't default, but whatever.
if utc:
date = date.replace(tzinfo=pytz.utc)
formula = "%Y-%m-%d"
return cls(date, formula)

Expand Down
7 changes: 6 additions & 1 deletion moment/date.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 4,7 @@

import calendar
from datetime import datetime, timedelta
import pytz

from .utils import _iteritems

Expand Down Expand Up @@ -120,7 121,11 @@ def replace(self, **kwds):
def epoch(self, rounding=True, milliseconds=False):
"""Milliseconds since epoch."""
zero = datetime.utcfromtimestamp(0)
delta = self._date - zero
try:
delta = self._date - zero
except TypeError:
zero = zero.replace(tzinfo=pytz.utc)
delta = self._date - zero
seconds = delta.total_seconds()
if rounding:
seconds = round(seconds)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 9,7 @@

setup(
name="moment",
version="0.6.1",
version="0.7",
url="http://github.com/zachwill/moment",
author="Zach Williams",
author_email="[email protected]",
Expand Down
4 changes: 2 additions & 2 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 59,8 @@ def test_moment_can_transfer_between_datetime_and_moment(self):
self.assertEqual(d, moment.date(d).date)

def test_moment_unix_command(self):
d = moment.unix(1355788800000, utc=True)
expected = moment.date((2012, 12, 18))
d = moment.unix(1355788800, utc=True).date
expected = moment.utc((2012, 12, 18)).date
self.assertEqual(d, expected)

def test_moment_can_subtract_another_moment(self):
Expand Down

0 comments on commit f3a0ffa

Please sign in to comment.