Python Pandas Timestamp 常用属性与方法详解
Python Pandas 库中 Timestamp 类的常用属性和方法,包括 value 属性获取纳秒值、week 和 weekofyear 属性获取周数、year 属性获取年份以及 as_unit 方法转换时间单位。内容涵盖各属性的语法、功能说明、返回值及具体的代码示例,帮助开发者高效处理时间数据。

Python Pandas 库中 Timestamp 类的常用属性和方法,包括 value 属性获取纳秒值、week 和 weekofyear 属性获取周数、year 属性获取年份以及 as_unit 方法转换时间单位。内容涵盖各属性的语法、功能说明、返回值及具体的代码示例,帮助开发者高效处理时间数据。

pandas.Timestamp.value
无
用于返回时间戳对应的纳秒级别的整数值,这对于处理时间数据,特别是在需要进行时间计算的场景中非常有用。
返回一个整数,表示自 Unix 纪元以来的纳秒数。
无
无
import pandas as pd
# 创建一个 Timestamp 对象
timestamp = pd.Timestamp('2024-10-13 21:53:56')
# 获取其对应的纳秒值
nanoseconds = timestamp.value
print(f'The Timestamp is: {timestamp}')
print(f'The number of nanoseconds since Unix epoch: {nanoseconds}')
The Timestamp is: 2024-10-13 21:53:56
The number of nanoseconds since Unix epoch: 1728856436000000000
pandas.Timestamp.week
无
用于获取时间戳所在年份的第几周。
返回一个整数,表示这一年份的第几周,按照 ISO 8601 标准计算。
无
无
import pandas as pd
# 创建一个 Timestamp 对象
timestamp = pd.Timestamp('2024-10-13')
# 获取该时间戳所在的周数
week_number = timestamp.week
print(f'The Timestamp is: {timestamp}')
print(f'The week number of the year is: {week_number}')
The Timestamp is: 2024-10-13 00:00:00
The week number of the year is: 41
pandas.Timestamp.weekofyear
无
一个已经被弃用的属性,用于获取时间戳在一年中的周数。虽然它在较早的版本中可用,但建议使用 pandas.Timestamp.isocalendar() 方法来获取更准确的信息。
返回时间戳在一年中的周数。
无
无
import pandas as pd
# 创建一个 Timestamp 对象
timestamp = pd.Timestamp('2024-10-13')
# 获取该时间戳的 ISO 年、周和周的一天
iso_calendar = timestamp.isocalendar()
# 返回一个元组 (year, week, weekday)
# 获取周数
week_of_year = iso_calendar[1]
print(f'The Timestamp is: {timestamp}')
print(f'The week number of the year is: {week_of_year}')
The Timestamp is: 2024-10-13 00:00:00
The week number of the year is: 41
pandas.Timestamp.year
无
用于获取 Timestamp 对象对应的年份,它的功能是提取时间戳表示日期的年份部分。
返回一个整数,表示年份。
无
无
import pandas as pd
# 创建一个 Timestamp 对象
ts = pd.Timestamp('2024-10-13 22:06:00')
# 获取年份
year = ts.year
print(year)
2024
pandas.Timestamp.as_unit(unit, round_ok=True)
**unit(必须):**字符串,指定所需的时间单位,支持的单位包括 's'(秒),'ms'(毫秒), 'us'(微秒)和'ns'(纳秒)。
**round_ok(可选,默认值为 True):**布尔值,指定是否允许四舍五入,当为 True 时,如果 Timestamp 无法精确地转换为指定的单位,会自动进行四舍五入;如果为 False,则抛出一个误差超过容差范围的异常。
将 Timestamp 对象转换为指定的时间单位,使之可以更方便地进行时间单位的精确操作,例如对不同时间单位间进行转换和比较。
返回一个新的 Timestamp 对象,这个对象表示转换为指定时间单位后的时间戳。
无
无
import pandas as pd
# 创建一个 Timestamp 对象
timestamp = pd.Timestamp('2024-10-13 22:16:56.789123456')
# 转换为秒
timestamp_sec = timestamp.as_unit('s')
print(timestamp_sec)
# 转换为毫秒
timestamp_ms = timestamp.as_unit('ms')
print(timestamp_ms)
2024-10-13 22:16:56
2024-10-13 22:16:56.789000

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online