Morrow.mojo:Mojo 的人类友好日期和时间 🔥
开源地址 : https://github.com/mojoto/morrow.mojo
![GitHub 发布](https://camo.githubusercontent.com/83fbc607b260202676ea1f93f2dbcf84eb4cebcd9dc637bbbc568bcfc13608d3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f6d6f6a6f746f2f6d6f72726f772e6d6f6a6f)
Morrow是一个 Mojo 库,它提供了人性化的方法来管理、格式化和转换日期、时间和时间戳。
Morrow 深受Arrow的启发,并感谢其优雅的设计。
特征
- 默认情况下支持时区和 UTC。
- 支持格式化和解析字符串。
- 支持ISO 8601标准。
准备
您可以通过三种方式引用该库:
- 从releases下载morrow.mojopkg 。
- 克隆该项目并执行
make build
以构建 morrow.mojopkg。
- 直接把
morrow
这个项目的目录复制到自己的项目中。
用法
from morrow import Morrow, TimeZone
# Get local date and time.
var now = Morrow.now()
print(str(now)) # 2023-10-01T20:10:25.188957+08:00
# Get UTC date and time.
var utcnow = Morrow.utcnow()
print(str(utcnow)) # 2023-10-01T20:10:25.954638+00:00
# Get local time from POSIX timestamp.
var t = Morrow.fromtimestamp(1696089600)
print(str(t)) # 2023-10-01T00:00:00.000000+08:00
# Get UTC time from POSIX timestamp.
var utc_t = Morrow.utcfromtimestamp(1696089600)
print(str(utc_t)) # 2023-09-30T16:00:00.000000+00:00
# Get ISO format.
var m = Morrow(2023, 10, 1, 0, 0, 0, 1234)
print(m.isoformat()) # 2023-10-01T00:00:00.001234
# custom format
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.
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.
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.
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.
var m_10_1_ = Morrow.fromordinal(ordinal)
print(str(m_10_1_)) # 2023-10-01T00:00:00.000000
# Convert Morrow to python datetime
var py_dt = now.to_py()
print(py_dt.isoformat()) # 2023-10-01T20:10:25.188957
# Convert python datetime to Morrow
var m_from_py = Morrow.from_py(py_dt)
print(m_from_py) # 2023-10-01T20:10:25.188957