Pandas pd.Timestamp() Function

Pandas 通用函数Commonly Used Pandas Functions


pd.Timestamp()is a function in the Pandas library forcreating timestamps.It can accept date-time input in multiple formats and return a precise Timestamp object.

Timestamp is a data type in Pandas used to represent a single point in time. It is an enhanced version of Python's standard library datetime.datetime, providing richer functionality and better performance.

Word Definition: TimestampMeans "timestamp", i.e., represents a specific moment in time.


Basic Syntax and Parameters

pd.Timestamp()is a top-level function of the Pandas library, used to create precise timestamp objects.

Syntax Format

pd.Timestamp(year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, nanosecond=None, tzinfo=None, freq=None)
pd.Timestamp(value)

Parameter Description

Parameter Type Required Description Default Value
value String, datetime, int, float Optional The time value to convert. None
year Integer Optional Year (4 digits). None
month Integer Optional Month (1-12). None
day Integer Optional Day (1-31). None
hour Integer Optional Hour (0-23). None
minute Integer Optional Minute (0-59). None
second Integer Optional Second (0-59). None
microsecond Integer Optional Microsecond (0-999999). None
nanosecond Integer Optional Nanosecond (0-999999). None
tz String or tzinfo Optional Timezone information, e.g., 'UTC', 'Asia/Shanghai'. None

Return Value Description

  • Return value: Returns a Timestamp object, similar to datetime.datetime.
  • Effect: Converts time data in various formats to precise Pandas timestamps.

Examples

Let's thoroughly master, through a series of examples from simple to complex,pd.Timestamp()the usage of pd.Timestamp().

Example 1: Basic Usage - Creating Timestamps

Example

import pandas as pd

# 1. Create a timestamp using a string
print("=== Create Timestamp from String ===")
ts1 = pd.Timestamp('2023-01-01')
print(f"pd.Timestamp('2023-01-01'): {ts1}")

ts2 = pd.Timestamp('2023-01-01 12:30:45')
print(f"pd.Timestamp('2023-01-01 12:30:45'): {ts2}")

ts3 = pd.Timestamp('2023-05-15 08:00:00.123456')
print(f"With microseconds: {ts3}")

# 2. Create a timestamp using keyword arguments
print("\n=== Keyword Arguments Creation ===")
ts4 = pd.Timestamp(year=2023, month=6, day=15, hour=10, minute=30)
print(f"pd.Timestamp(year=2023, month=6, day=15, hour=10, minute=30): {ts4}")

# 3. Create from a datetime object
print("\n=== Create from datetime object ===")
import datetime
dt = datetime.datetime(2023, 8, 20, 14, 45, 30)
ts5 = pd.Timestamp(dt)
print(f"Created from datetime: {ts5}")

# 4. View timestamp attributes
print("\n=== Timestamp Attributes ===")
ts = pd.Timestamp('2023-03-15 10:30:45.123456')
print(f"Timestamp: {ts}")
print(f"Year: {ts.year}")
print(f"Month: {ts.month}")
print(f"Day: {ts.day}")
print(f"Hour: {ts.hour}")
print(f"Minute: {ts.minute}")
print(f"Second: {ts.second}")
print(f"Microsecond: {ts.microsecond}")
print(f"Day of week (0=Monday): {ts.dayofweek}")
print(f"Quarter: {ts.quarter}")

Output:

=== 字符串创建时间戳 ===
pd.Timestamp('2023-01-01'): 2023-01-01 00:00:00
pd.Timestamp('2023-01-01 12:30:45'): 2023-01-01 12:30:45
带微秒: 2023-05-15 08:00:00.123456

=== 关键字参数创建 ===
pd.Timestamp(year=2023, month=6, day=15, hour=10, minute=30): 2023-06-15 10:30:00

=== datetime 对象创建 ===
从 datetime 创建: 2023-08-20 14:45:30

=== 时间戳属性 ===
时间戳: 2023-03-15 10:30:45.123456
年份: 2023
月份: 3
日期: 15
小时: 10
分钟: 30
秒: 45
微秒: 123456
星期几 (0=周一): 2
季度: 1

Code analysis:

  1. pd.Timestamp()It can accept input in multiple formats, including strings, datetime objects, etc.
  2. Timestamp provides rich attributes to access various parts of the date and time.
  3. dayofweekReturns 0-6, where 0 represents Monday.

Example 2: Timezone Handling

Example

import pandas as pd

# 1. Create a timestamp with a timezone
print("=== Create Timestamp with Timezone ===")
ts_utc = pd.Timestamp('2023-01-01 12:00:00', tz='UTC')
print(f"UTC timezone: {ts_utc}")

ts_shanghai = pd.Timestamp('2023-01-01 20:00:00', tz='Asia/Shanghai')
print(f"Shanghai timezone: {ts_shanghai}")

# 2. Conversion between different timezones
print("\n=== Timezone Conversion ===")
ts_utc = pd.Timestamp('2023-01-01 12:00:00', tz='UTC')
ts_local = ts_utc.tz_convert('Asia/Shanghai')
print(f"UTC time: {ts_utc}")
print(f"Converted to Shanghai: {ts_local}")

# 3. Create a local timezone timestamp (convert from naive to aware)
print("\n=== Convert Local Time to Timezone-aware ===")
ts_naive = pd.Timestamp('2023-01-01 12:00:00')
print(f"Naive (no timezone): {ts_naive}")
ts_aware = ts_naive.tz_localize('Asia/Shanghai')
print(f"Added Shanghai timezone: {ts_aware}")

# 4. Use shorthand forms of the tz parameter
print("\n=== Timezone Shorthand ===")
ts1 = pd.Timestamp('2023-01-01 12:00', tz='US/Eastern')
print(f"US Eastern: {ts1}")
ts2 = pd.Timestamp('2023-01-01 12:00', tz='Europe/London')
print(f"London: {ts2}")

Output:

=== 创建带时区的时间戳 ===
UTC 时区: 2023-01-01 12:00:00+00:00
上海时区: 2023-01-01 20:00:00+08:00

=== 时区转换 ===
UTC 时间: 2023-01-01 12:00:00+00:00
转换到上海: 2023-01-01 20:00:00+08:00

=== 本地时间转带时区 ===
无时区: 2023-01-01 12:00:00
添加上海时区: 2023-01-01 12:00:00+08:00

=== 时区简写 ===
美国东部: 2023-01-01 12:00:00-05:00
伦敦: 2023-01-01 12:00:00+00:00

Code analysis:

  • tz_localizeUsed to add timezone information to a naive Timestamp.
  • tz_convertUsed to convert between different timezones.

Example 3: Timestamp Comparison and Operations

Example

import pandas as pd

# 1. Timestamp comparison
print("=== Timestamp Comparison ===")
ts1 = pd.Timestamp('2023-01-01')
ts2 = pd.Timestamp('2023-01-15')
ts3 = pd.Timestamp('2023-01-01')

print(f"ts1: {ts1}")
print(f"ts2: {ts2}")
print(f"ts1 < ts2: {ts1 < ts2}")
print(f"ts1 == ts3: {ts1 == ts3}")
print(f"ts1 != ts2: {ts1 != ts2}")

# 2. Operations between Timestamp and Timedelta
print("\n=== Timestamp and Timedelta Operations ===")
ts = pd.Timestamp('2023-01-01 12:00:00')
td = pd.Timedelta(days=5, hours=3)

print(f"Original timestamp: {ts}")
print(f"Timedelta: {td}")
print(f"ts + td: {ts + td}")
print(f"ts - td: {ts - td}")

# 3. Subtract two timestamps to get a Timedelta
print("\n=== Subtracting Two Timestamps ===")
ts1 = pd.Timestamp('2023-01-15 18:00:00')
ts2 = pd.Timestamp('2023-01-10 09:00:00')

diff = ts1 - ts2
print(f"ts1: {ts1}")
print(f"ts2: {ts2}")
print(f"ts1 - ts2: {diff}")
print(f"Days: {diff.days}")
print(f"Hours: {diff.seconds / 3600}")

# 4. Use timestamps in DataFrame
print("\n=== Timestamps in DataFrame ===")
df = pd.DataFrame({
    'event': ['event_a', 'event_b', 'event_c'],
    'timestamp': [
        pd.Timestamp('2023-01-01 10:00:00'),
        pd.Timestamp('2023-01-02 15:30:00'),
        pd.Timestamp('2023-01-03 09:45:00')
    ]
})
print(df)
print(f"\nEvent duration (relative to the first event):")
df['relative_days'] = (df['timestamp'] - df['timestamp'].iloc[0]).dt.days
print(df)

Output:

=== 时间戳比较 ===
ts1: 2023-01-01 00:00:00
ts2: 2023-01-15 00:00:00
ts1 < ts2: True
ts1 == ts3: True
ts1 != ts2: True

=== 时间戳与时间差运算 ===
原时间戳: 2023-01-01 12:00:00
时间差: 5 days 03:00:00
ts + td: 2023-01-06 15:00:00
ts - td: 2022-12-27 09:00:00

=== 两个时间戳相减 ===
ts1: 2023-01-15 18:00:00
ts2: 2023-01-10 09:00:00
ts1 - ts2: 5 days 09:00:00
天数: 5
小时: 9.0

=== DataFrame 中的时间戳 ===
        event           timestamp
0  event_a  2023-01-01 10:00:00
1  event_b  2023-01-02 15:30:00
2  event_c  2023-01-03 09:45:00

事件持续时间(相对于第一个事件):
        event           timestamp  relative_days
0  event_a  2023-01-01 10:00:00             0
1  event_b  2023-01-02 15:30:00             1
2  event_c  2023-01-03 09:45:00             2

Code analysis:

  • Timestamp supports direct comparison operators (>, <, ==, !=).
  • Adding or subtracting a Timedelta to/from a Timestamp yields a new Timestamp or Timedelta.
  • Subtracting two timestamps yields a Timedelta object.
  • Time-related calculations can be conveniently performed in DataFrame.

Important Notes

Important note:

  • pd.TimestampSimilar to Python's datetime, but provides higher performance and more methods.
  • Timestamp objects are immutable; modification operations return new objects.
  • Timezone information is best specified at creation time; modifying the timezone later may cause ambiguity.
  • Use NaTpd.NaT(Not a Time) to represent missing time values.

Pandas 通用函数Commonly Used Pandas Functions

Other Extensions