Skip to content

Commit

Permalink
feat: adapt to mojo v24.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Prodesire committed Mar 11, 2024
1 parent 8ff075a commit c1bfaff
Show file tree
Hide file tree
Showing 11 changed files with 91 additions and 96 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: Run Tests

on: [pull_request]
on: [pull_request, push]

env:
PACKAGE_NAME: morrow.mojopkg
Expand Down
26 changes: 13 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,57 +33,57 @@ You have three ways to reference this library:
from morrow import Morrow, TimeZone

# Get local date and time.
let now = Morrow.now()
var now = Morrow.now()
print(str(now)) # 2023-10-01T20:10:25.188957+08:00

# Get UTC date and time.
let utcnow = Morrow.utcnow()
var utcnow = Morrow.utcnow()
print(str(utcnow)) # 2023-10-01T20:10:25.954638+00:00

# Get local time from POSIX timestamp.
let t = Morrow.fromtimestamp(1696089600)
var t = Morrow.fromtimestamp(1696089600)
print(str(t)) # 2023-10-01T00:00:00.000000+08:00

# Get UTC time from POSIX timestamp.
let utc_t = Morrow.utcfromtimestamp(1696089600)
var utc_t = Morrow.utcfromtimestamp(1696089600)
print(str(utc_t)) # 2023-09-30T16:00:00.000000+00:00

# Get ISO format.
let m = Morrow(2023, 10, 1, 0, 0, 0, 1234)
var m = Morrow(2023, 10, 1, 0, 0, 0, 1234)
print(m.isoformat()) # 2023-10-01T00:00:00.001234

# custom format
let m = Morrow(2023, 10, 1, 0, 0, 0, 1234)
var m = Morrow(2023, 10, 1, 0, 0, 0, 1234)
print(m.format("YYYY-MM-DD HH:mm:ss.SSSSSS ZZ")) # 2023-10-01 00:00:00.001234 +00:00
print(m.format("dddd, DD MMM YYYY HH:mm:ss ZZZ")) # Sunday, 01 Oct 2023 00:00:00 UTC
print(m.format("YYYY[Y]MM[M]DD[D]")) # 2023Y10M01D

# Get ISO format with time zone.
let m_beijing = Morrow(2023, 10, 1, 0, 0, 0, 1234, TimeZone(28800, 'Bejing'))
var m_beijing = Morrow(2023, 10, 1, 0, 0, 0, 1234, TimeZone(28800, 'Bejing'))
print(m_beijing.isoformat(timespec="seconds")) # 2023-10-01T00:00:00+08:00

# Get time zone offset.
print(TimeZone.from_utc('UTC+08:00').offset) # 28800

# Subtract two dates.
let timedelta = Morrow(2023, 10, 2, 10, 0, 0) - Morrow(2023, 10, 1, 10, 0, 0)
var timedelta = Morrow(2023, 10, 2, 10, 0, 0) - Morrow(2023, 10, 1, 10, 0, 0)
print(str(timedelta)) # 1 day, 0:00:00

# Return proleptic Gregorian ordinal for the year, month and day.
let m_10_1 = Morrow(2023, 10, 1)
let ordinal = m_10_1.toordinal()
var m_10_1 = Morrow(2023, 10, 1)
var ordinal = m_10_1.toordinal()
print(ordinal) # 738794

# Construct a Morrow from a proleptic Gregorian ordinal.
let m_10_1_ = Morrow.fromordinal(ordinal)
var m_10_1_ = Morrow.fromordinal(ordinal)
print(str(m_10_1_)) # 2023-10-01T00:00:00.000000

# Convert Morrow to python datetime
let py_dt = now.to_py()
var py_dt = now.to_py()
print(py_dt.isoformat()) # 2023-10-01T20:10:25.188957

# Convert python datetime to Morrow
let m_from_py = Morrow.from_py(py_dt)
var m_from_py = Morrow.from_py(py_dt)
print(m_from_py) # 2023-10-01T20:10:25.188957

```
2 changes: 1 addition & 1 deletion morrow/__init__.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ from .morrow import Morrow
from .timezone import TimeZone
from .timedelta import TimeDelta

alias __version__ = "0.3.0"
alias __version__ = "0.3.1"
16 changes: 8 additions & 8 deletions morrow/_libc.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,22 @@ struct CTm:
@always_inline
fn c_gettimeofday() -> CTimeval:
var tv = CTimeval()
let p_tv = Pointer[CTimeval].address_of(tv)
var p_tv = Pointer[CTimeval].address_of(tv)
external_call["gettimeofday", NoneType, Pointer[CTimeval], Int32](p_tv, 0)
return tv


@always_inline
fn c_localtime(owned tv_sec: Int) -> CTm:
let p_tv_sec = Pointer[Int].address_of(tv_sec)
let tm = external_call["localtime", Pointer[CTm], Pointer[Int]](p_tv_sec).load()
var p_tv_sec = Pointer[Int].address_of(tv_sec)
var tm = external_call["localtime", Pointer[CTm], Pointer[Int]](p_tv_sec).load()
return tm


@always_inline
fn c_strptime(time_str: String, time_format: String) -> CTm:
var tm = CTm()
let p_tm = Pointer[CTm].address_of(tm)
var p_tm = Pointer[CTm].address_of(tm)
external_call["strptime", NoneType, Pointer[c_char], Pointer[c_char], Pointer[CTm]](
to_char_ptr(time_str), to_char_ptr(time_format), p_tm
)
Expand All @@ -81,14 +81,14 @@ fn c_strptime(time_str: String, time_format: String) -> CTm:

@always_inline
fn c_gmtime(owned tv_sec: Int) -> CTm:
let p_tv_sec = Pointer[Int].address_of(tv_sec)
let tm = external_call["gmtime", Pointer[CTm], Pointer[Int]](p_tv_sec).load()
var p_tv_sec = Pointer[Int].address_of(tv_sec)
var tm = external_call["gmtime", Pointer[CTm], Pointer[Int]](p_tv_sec).load()
return tm


fn to_char_ptr(s: String) -> Pointer[c_char]:
"""only ASCII-based strings"""
let ptr = Pointer[c_char]().alloc(len(s))
"""Only ASCII-based strings."""
var ptr = Pointer[c_char]().alloc(len(s))
for i in range(len(s)):
ptr.store(i, ord(s[i]))
return ptr
4 changes: 2 additions & 2 deletions morrow/_py.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ from python import Python


fn py_dt_datetime() raises -> PythonObject:
let _datetime = Python.import_module("datetime")
var _datetime = Python.import_module("datetime")
return _datetime.datetime


fn py_time() raises -> PythonObject:
let _time = Python.import_module("time")
var _time = Python.import_module("time")
return _time
2 changes: 1 addition & 1 deletion morrow/formatter.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ struct _Formatter:
var match_chr_ord = 0
var match_count = 0
for i in range(len(s)):
let c = ord(s[i])
var c = ord(s[i])
if 0 < c < 128 and self._sub_chrs[c] > 0:
if c == match_chr_ord:
match_count += 1
Expand Down
52 changes: 26 additions & 26 deletions morrow/morrow.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -48,26 +48,26 @@ struct Morrow(StringableRaising):

@staticmethod
fn now() raises -> Self:
let t = c_gettimeofday()
var t = c_gettimeofday()
return Self._fromtimestamp(t, False)

@staticmethod
fn utcnow() raises -> Self:
let t = c_gettimeofday()
var t = c_gettimeofday()
return Self._fromtimestamp(t, True)

@staticmethod
fn _fromtimestamp(t: CTimeval, utc: Bool) raises -> Self:
let tm: CTm
let tz: TimeZone
var tm: CTm
var tz: TimeZone
if utc:
tm = c_gmtime(t.tv_sec)
tz = TimeZone(0, "UTC")
else:
tm = c_localtime(t.tv_sec)
tz = TimeZone(tm.tm_gmtoff.to_int(), "local")

let result = Self(
var result = Self(
tm.tm_year.to_int() + 1900,
tm.tm_mon.to_int() + 1,
tm.tm_mday.to_int(),
Expand All @@ -81,14 +81,14 @@ struct Morrow(StringableRaising):

@staticmethod
fn fromtimestamp(timestamp: Float64) raises -> Self:
let timestamp_ = normalize_timestamp(timestamp)
let t = CTimeval(timestamp_.to_int())
var timestamp_ = normalize_timestamp(timestamp)
var t = CTimeval(timestamp_.to_int())
return Self._fromtimestamp(t, False)

@staticmethod
fn utcfromtimestamp(timestamp: Float64) raises -> Self:
let timestamp_ = normalize_timestamp(timestamp)
let t = CTimeval(timestamp_.to_int())
var timestamp_ = normalize_timestamp(timestamp)
var t = CTimeval(timestamp_.to_int())
return Self._fromtimestamp(t, True)

@staticmethod
Expand All @@ -104,8 +104,8 @@ struct Morrow(StringableRaising):
>>> Morrow.strptime('20-01-2019 15:49:10', '%d-%m-%Y %H:%M:%S')
<Morrow [2019-01-20T15:49:10+00:00]>
"""
let tm = c_strptime(date_str, fmt)
let tz = TimeZone(tm.tm_gmtoff.to_int()) if tzinfo.is_none() else tzinfo
var tm = c_strptime(date_str, fmt)
var tz = TimeZone(tm.tm_gmtoff.to_int()) if tzinfo.is_none() else tzinfo
return Self(
tm.tm_year.to_int() + 1900,
tm.tm_mon.to_int() + 1,
Expand All @@ -120,14 +120,14 @@ struct Morrow(StringableRaising):
@staticmethod
fn strptime(date_str: String, fmt: String, tz_str: String) raises -> Self:
"""
Create a Morrow instance by time_zone_string with utc format
Create a Morrow instance by time_zone_string with utc format.
Usage::
>>> Morrow.strptime('20-01-2019 15:49:10', '%d-%m-%Y %H:%M:%S', '+08:00')
<Morrow [2019-01-20T15:49:10+08:00]>
"""
let tzinfo = TimeZone.from_utc(tz_str)
var tzinfo = TimeZone.from_utc(tz_str)
return Self.strptime(date_str, fmt, tzinfo)

fn format(self, fmt: String = "YYYY-MM-DD HH:mm:ss ZZ") raises -> String:
Expand All @@ -137,7 +137,7 @@ struct Morrow(StringableRaising):
:param fmt: the format string.
Usage::
>>> let m = Morrow.now()
>>> var m = Morrow.now()
>>> m.format('YYYY-MM-DD HH:mm:ss ZZ')
'2013-05-09 03:56:47 -00:00'
Expand Down Expand Up @@ -167,7 +167,7 @@ struct Morrow(StringableRaising):
terms of the time to include. Valid options are 'auto', 'hours',
'minutes', 'seconds', 'milliseconds' and 'microseconds'.
"""
let date_str = (
var date_str = (
rjust(self.year, 4, "0")
+ "-"
+ rjust(self.month, 2, "0")
Expand Down Expand Up @@ -251,7 +251,7 @@ struct Morrow(StringableRaising):
# 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
var n = ordinal
n -= 1
let n400 = n // _DI400Y
var n400 = n // _DI400Y
n = n % _DI400Y
var year = n400 * 400 + 1 # ..., -399, 1, 401, ...

Expand All @@ -260,16 +260,16 @@ struct Morrow(StringableRaising):
# Note that it's possible for n100 to equal 4! In that case 4 full
# 100-year cycles precede the desired day, which implies the desired
# day is December 31 at the end of a 400-year cycle.
let n100 = n // _DI100Y
var n100 = n // _DI100Y
n = n % _DI100Y

# Now compute how many 4-year cycles precede it.
let n4 = n // _DI4Y
var n4 = n // _DI4Y
n = n % _DI4Y

# And now how many single years. Again n1 can be 4, and again meaning
# that the desired day is December 31 at the end of the 4-year cycle.
let n1 = n // 365
var n1 = n // 365
n = n % 365

year += n100 * 100 + n4 * 4 + n1
Expand All @@ -278,7 +278,7 @@ struct Morrow(StringableRaising):

# Now the year is correct, and n is the offset from January 1. We find
# the month via an estimate that's either exact or one too large.
let leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
var leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
var month = (n + 50) >> 5
var preceding: Int
if month > 2 and leapyear:
Expand Down Expand Up @@ -306,18 +306,18 @@ struct Morrow(StringableRaising):
return self.isoformat()

fn __sub__(self, other: Self) raises -> TimeDelta:
let days1 = self.toordinal()
let days2 = other.toordinal()
let secs1 = self.second + self.minute * 60 + self.hour * 3600
let secs2 = other.second + other.minute * 60 + other.hour * 3600
let base = TimeDelta(
var days1 = self.toordinal()
var days2 = other.toordinal()
var secs1 = self.second + self.minute * 60 + self.hour * 3600
var secs2 = other.second + other.minute * 60 + other.hour * 3600
var base = TimeDelta(
days1 - days2, secs1 - secs2, self.microsecond - other.microsecond
)
return base

fn to_py(self) raises -> PythonObject:
# todo: add tz later
let dateimte = Python.import_module("datetime")
var dateimte = Python.import_module("datetime")
return dateimte.datetime(
self.year,
self.month,
Expand Down
6 changes: 3 additions & 3 deletions morrow/timedelta.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ struct TimeDelta(Stringable):

fn __str__(self) -> String:
var mm = self.seconds // 60
let ss = self.seconds % 60
let hh = mm // 60
var ss = self.seconds % 60
var hh = mm // 60
mm = mm % 60
var s = String(hh) + ":" + rjust(mm, 2, "0") + ":" + rjust(ss, 2, "0")
if self.days:
Expand Down Expand Up @@ -130,7 +130,7 @@ struct TimeDelta(Stringable):
return (self.days * SECONDS_OF_DAY + self.seconds) * 1000000 + self.microseconds

fn __mod__(self, other: Self) -> Self:
let r = self._to_microseconds() % other._to_microseconds()
var r = self._to_microseconds() % other._to_microseconds()
return Self(0, 0, r)

fn __eq__(self, other: Self) -> Bool:
Expand Down
18 changes: 9 additions & 9 deletions morrow/timezone.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ struct TimeZone(Stringable):

@staticmethod
fn local() -> TimeZone:
let local_t = c_localtime(0)
var local_t = c_localtime(0)
return TimeZone(local_t.tm_gmtoff.to_int(), "local")

@staticmethod
Expand All @@ -36,7 +36,7 @@ struct TimeZone(Stringable):
return TimeZone(0, "utc")
var p = 3 if len(utc_str) > 3 and utc_str[0:3] == "UTC" else 0

let sign = -1 if utc_str[p] == "-" else 1
var sign = -1 if utc_str[p] == "-" else 1
if utc_str[p] == "+" or utc_str[p] == "-":
p += 1

Expand All @@ -46,10 +46,10 @@ struct TimeZone(Stringable):
or not isdigit(ord(utc_str[p + 1]))
):
raise Error("utc_str format is invalid")
let hours: Int = atol(utc_str[p : p + 2])
var hours: Int = atol(utc_str[p : p + 2])
p += 2

let minutes: Int
var minutes: Int
if len(utc_str) <= p:
minutes = 0
elif len(utc_str) == p + 3 and utc_str[p] == ":":
Expand All @@ -59,18 +59,18 @@ struct TimeZone(Stringable):
else:
minutes = 0
raise Error("utc_str format is invalid")
let offset: Int = sign * (hours * 3600 + minutes * 60)
var offset: Int = sign * (hours * 3600 + minutes * 60)
return TimeZone(offset)

fn format(self, sep: String = ":") -> String:
let sign: String
let offset_abs: Int
var sign: String
var offset_abs: Int
if self.offset < 0:
sign = "-"
offset_abs = -self.offset
else:
sign = "+"
offset_abs = self.offset
let hh = offset_abs // 3600
let mm = offset_abs % 3600
var hh = offset_abs // 3600
var mm = offset_abs % 3600
return sign + rjust(hh, 2, "0") + sep + rjust(mm, 2, "0")
Loading

0 comments on commit c1bfaff

Please sign in to comment.