Ruby 日期与时间(Date & Time)
讲解 Ruby Time 类创建当前时间、读取时间组件与 to_a 数组、UTC/本地时区构造与纪元时间戳转换、strftime 格式化指令及时间加减运算。
学完这一章,你能够
- 讲解 Ruby Time 类创建当前时间、读取时间组件与 to_a 数组、UTC/本地时区构造与纪元时间戳转换、strftime 格式化指令及时间加减运算。
创建 Time 对象与读取日期时间组件
在 Ruby 中,`Time` 类用于表示具体的日期与时刻。早期 32 位系统上 `Time` 受限于 `time_t` 范围(1970 年至 2038 年),但在现代 64 位 Ruby 3.x 中 `Time` 已采用更大位宽整数并支持纳秒精度。获取当前系统时间可直接调用 `Time.new` 或等价的 `Time.now`,两者均返回带本地时区偏移的 `Time` 实例,调用 `inspect` 或 `to_s` 可格式化输出如 `2015-09-17 15:23:14 +0800` 的字符串。
`Time` 对象内置了丰富的分量读取方法:`year`、`month`(1–12)、`day`(1–31)返回年月日;`wday` 返回星期几(0 代表星期日,6 代表星期六),`yday` 返回一年中的第几天(1–366);`hour`(24 小时制)、`min`、`sec`、`usec`(微秒)返回时分秒细节,`zone` 则给出当前时区缩写名称(如 `CST` 或 `UTC`)。
构造特定时间、数组拆包与时区管理
除了获取当前时刻,还可用 `Time.local`、`Time.utc` 和 `Time.gm`(与 `utc` 等价)按年、月、日、时、分、秒显式构造指定时刻。调用 `time.to_a` 会返回固定顺序的 10 元数组 `[sec, min, hour, day, month, year, wday, yday, isdst, zone]`,可直接通过 `*values` 展开后传给 `Time.utc(*values)` 或 `Time.local(*values)` 重建时间对象。若需与 Unix 纪元秒数互转,可使用 `Time.now.to_i`(整数秒)、`Time.now.to_f`(含微秒的浮点秒)以及 `Time.at(seconds)`。
时区与夏令时属性同样可通过实例方法查询与切换:`utc_offset` 返回相对 UTC 的偏移秒数(东八区为 `28800`),`isdst` 判断是否处于夏令时,`utc?` 检查是否为 UTC 时区;`localtime` 与 `gmtime` 会原地修改当前对象时区,而 `getlocal` 与 `getutc` 则不改原对象、返回一个新时区的 `Time` 副本,工程中更推荐不可变风格的 `getlocal`/`getutc`。
格式化输出、strftime 指令与时间算术
`Time` 提供 `to_s`、`ctime`(英文星期月份标准格式)及 `strftime` 等多种格式化手段。`strftime` 接收由 `%` 开头的格式指令串(如 `time.strftime("%Y-%m-%d %H:%M:%S")`),完整指令含义见下表;需注意 `%w` 以周日为 0,`%U` 与 `%W` 分别以周日和周一作为第一周起点。
`Time` 支持直观的时间算术:`Time + number` 或 `Time - number` 以秒为单位前后偏移并返回一个新的 `Time` 对象(例如 `now - 10` 为 10 秒前,`now + 10` 为 10 秒后);两个 `Time` 对象相减(`future - now`)则返回两者相差的浮点秒数(如 `10.0`)。
Ruby Time#strftime 常用格式化指令
| 指令 | 说明 |
|---|---|
| %a | 星期名称英文缩写(如 Sun、Thu)。 |
| %A | 星期名称英文全称(如 Sunday、Thursday)。 |
| %b | 月份名称英文缩写(如 Jan、Sep)。 |
| %B | 月份名称英文全称(如 January、September)。 |
| %c | 区域首选的完整日期与时间表示法。 |
| %d | 两位补零的月中日期(01–31)。 |
| %H | 24 小时制两位小时数(00–23)。 |
| %I | 12 小时制两位小时数(01–12)。 |
| %j | 三位补零的年内第几天(001–366)。 |
| %m | 两位补零月份(01–12)。 |
| %M | 两位补零分钟数(00–59)。 |
| %p | 上午或下午标记(AM / PM)。 |
| %S | 两位补零秒数(00–60,含闰秒)。 |
| %U | 年内周数(00–53),以首个星期日作为第 1 周首日。 |
| %W | 年内周数(00–53),以首个星期一作为第 1 周首日。 |
| %w | 星期数字编号(0 表示星期日,范围 0–6)。 |
| %x | 区域首选的仅日期表示法。 |
| %X | 区域首选的仅时间表示法。 |
| %y | 不含世纪的两位年份(00–99)。 |
| %Y | 包含世纪的四位完整年份。 |
| %Z | 当前时区名称或缩写(如 UTC、CST)。 |
| %% | 输出字面量百分号 % 字符本身。 |
离线校验 Ruby Time 组件、to_a、时区偏移、strftime 与时间算术
"""Offline Ruby 3.x semantic verification lab for Chapter 24 (date-time)."""
import datetime as dt
import json
import shutil
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def case_time_components_and_to_a():
# Ruby Time#to_a order: [sec, min, hour, day, month, year, wday(Sun=0), yday, isdst, zone]
tz_cst = dt.timezone(dt.timedelta(hours=8), name="CST")
t = dt.datetime(2015, 9, 17, 15, 24, 44, 921519, tzinfo=tz_cst)
ruby_wday = (t.weekday() + 1) % 7 # Python Mon=0..Sun=6 -> Ruby Sun=0..Sat=6
yday = t.timetuple().tm_yday
to_a = [t.second, t.minute, t.hour, t.day, t.month, t.year, ruby_wday, yday, False, t.tzname()]
expected = {
"ruby_absent": True,
"inspect": "2015-09-17 15:24:44 +0800",
"year": 2015,
"month": 9,
"day": 17,
"wday": 4,
"yday": 260,
"usec": 921519,
"to_a": [44, 24, 15, 17, 9, 2015, 4, 260, False, "CST"],
}
actual = {
"ruby_absent": shutil.which("ruby") is None,
"inspect": t.strftime("%Y-%m-%d %H:%M:%S %z"),
"year": t.year,
"month": t.month,
"day": t.day,
"wday": ruby_wday,
"yday": yday,
"usec": t.microsecond,
"to_a": to_a,
}
return {
"name": "time_components_and_to_a",
"summary": "核验 Ruby Time 组件读取(年/月/日/星期/年日/微秒)与 to_a 10 元素数组顺序,以及本机无 MRI Ruby 探测",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_utc_local_and_epoch():
tz_cst = dt.timezone(dt.timedelta(hours=8), name="CST")
t_utc = dt.datetime(2008, 7, 8, 9, 10, 11, tzinfo=dt.timezone.utc)
t_local = t_utc.astimezone(tz_cst)
epoch_i = int(t_utc.timestamp())
rebuilt = dt.datetime.fromtimestamp(epoch_i, tz=dt.timezone.utc)
expected = {
"utc_str": "2008-07-08 09:10:11 UTC",
"local_str": "2008-07-08 17:10:11 +0800",
"utc_offset_sec": 0,
"cst_offset_sec": 28800,
"is_utc": True,
"epoch_roundtrip": True,
}
actual = {
"utc_str": t_utc.strftime("%Y-%m-%d %H:%M:%S UTC"),
"local_str": t_local.strftime("%Y-%m-%d %H:%M:%S %z"),
"utc_offset_sec": int(t_utc.utcoffset().total_seconds()),
"cst_offset_sec": int(t_local.utcoffset().total_seconds()),
"is_utc": t_utc.utcoffset() == dt.timedelta(0),
"epoch_roundtrip": rebuilt == t_utc,
}
return {
"name": "utc_local_and_epoch",
"summary": "核验 Time.utc/Time.gm/Time.local 时区偏移、getlocal/getutc 转换与纪元秒数 Time.at 往返一致",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_strftime_directives():
tz_cst = dt.timezone(dt.timedelta(hours=8), name="CST")
t = dt.datetime(2015, 9, 17, 15, 26, 42, tzinfo=tz_cst)
ruby_wday = str((t.weekday() + 1) % 7)
directives = {
"%Y-%m-%d %H:%M:%S": t.strftime("%Y-%m-%d %H:%M:%S"),
"%a": t.strftime("%a"),
"%A": t.strftime("%A"),
"%b": t.strftime("%b"),
"%B": t.strftime("%B"),
"%I %p": t.strftime("%I %p"),
"%j": t.strftime("%j"),
"%U": t.strftime("%U"),
"%W": t.strftime("%W"),
"%w": ruby_wday,
"%y": t.strftime("%y"),
"%Z": t.tzname(),
"%%": t.strftime("%%"),
}
expected = {
"%Y-%m-%d %H:%M:%S": "2015-09-17 15:26:42",
"%a": "Thu",
"%A": "Thursday",
"%b": "Sep",
"%B": "September",
"%I %p": "03 PM",
"%j": "260",
"%U": "37",
"%W": "37",
"%w": "4",
"%y": "15",
"%Z": "CST",
"%%": "%",
}
return {
"name": "strftime_directives",
"summary": "核验 Time#strftime 全部核心格式化指令输出(日期、12/24 小时制、周数、百分号转义)",
"expected": expected,
"actual": directives,
"passed": directives == expected,
}
def case_time_arithmetic_and_offset():
tz_cst = dt.timezone(dt.timedelta(hours=8), name="CST")
now = dt.datetime(2015, 9, 17, 15, 27, 8, tzinfo=tz_cst)
past = now - dt.timedelta(seconds=10)
future = now + dt.timedelta(seconds=10)
diff = (future - now).total_seconds()
expected = {
"past": "2015-09-17 15:26:58 +0800",
"future": "2015-09-17 15:27:18 +0800",
"diff_seconds": 10.0,
}
actual = {
"past": past.strftime("%Y-%m-%d %H:%M:%S %z"),
"future": future.strftime("%Y-%m-%d %H:%M:%S %z"),
"diff_seconds": diff,
}
return {
"name": "time_arithmetic_and_offset",
"summary": "核验 Time 加减秒数返回新 Time、两 Time 相减返回浮点秒数差值的语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_time_components_and_to_a(),
case_utc_local_and_epoch(),
case_strftime_directives(),
case_time_arithmetic_and_offset(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 4 个确定性用例全部通过,准确验证 Time 组件与 to_a 顺序、UTC/+0800 偏移、strftime 指令及加减 10 秒运算。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
当前源码 SHA256:50cf884d6089c892d99b163092f519eff53c284d83d2e5ac799f9947b8f3babb
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
ZIP SHA256:5b810bd2814d22f0a22416e351d98db44945801a9f563dfa6ff7298fdfa35606
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`time.gmtime` 与 `time.getutc` 都能得到 UTC 时间,二者的核心区别是什么?
展开参考解答
`gmtime` 会原地修改原 `Time` 对象的时区状态,而 `getutc` 保持原对象不变并返回一个新的 UTC `Time` 对象。