Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.Timestamp() function

Pandas pd.Timestamp() function

Pandas Universal Functions Common Pandas functions


pd.Timestamp() is a function in the Pandas library used toCreate a timestampfunction. It can accept date-time input in many formats and returns a precise Timestamp object.

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

Word meaning: Timestamp It means "timestamp", i.e., a specific moment in time.


Basic syntax and parameters

pd.Timestamp() is a top-level function in 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

Parameters Type Required Description Default value
value str, datetime, int, float Optional The time value to convert. None
year Integers Optional Year (4 digits). None
month Integers Optional Month (1-12). None
day Integers Optional Day (1-31). None
hour Integers Optional Hour (0-23). None
minute Integers Optional Minute (0-59). None
second Integers Optional Second (0-59). None
microsecond Integers Optional Microsecond (0-999999). None
nanosecond Integers Optional Nanosecond (0-999999). None
tz str or tzinfo Optional Time zone information, such as 'UTC' or 'Asia/Shanghai'. None

Return value description


Example

Let us thoroughly master pd.Timestamp() through a series of examples from simple to complex.

Example 1: Basic usage - creating a timestamp

Example

import

pandas

as

pd

1. Creating a timestamp from 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. Creating a timestamp with keyword arguments

print

(

"n=== Create with keyword arguments ==="

)

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. Creating 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. Viewing 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}"

)

Result:



=== 字符串创建时间戳 ===

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 accepts input in many formats, including strings, datetime objects, and more.
  2. Timestamps provide rich attributes for accessing the parts of a date-time value.
  3. dayofweek It returns 0-6, where 0 means Monday.

Example 2: Time zone handling

Example

import

pandas

as

pd

1. Creating a timezone-aware timestamp

print

(

"=== Create a timezone-aware timestamp ==="

)

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. Converting between time zones

print

(

"n=== Time zone 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. Creating a timestamp in local time (naive to timezone-aware)

print

(

"n=== Naive 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. Using the shorthand form of the tz argument

print

(

"n=== Time zone 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}"

)

Result:



=== 创建带时区的时间戳 ===

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:

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 a timestamp and a Timedelta

print

(

"n=== Timestamp and time difference operations ==="

)

ts

=

pd.

Timestamp

(

'2023-01-01 12:00:00'

)

td

=

pd.

Timedelta

(

days

=

5

,

hours

=

3

)

print

(

f

"Original timestamp: {ts}"

)

print

(

f

"Time difference: {td}"

)

print

(

f

"ts + td: {ts + td}"

)

print

(

f

"ts - td: {ts - td}"

)

3. Subtracting two timestamps to get a Timedelta

print

(

"n=== Subtract 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. Using timestamps in a DataFrame

print

(

"n=== Timestamps in a 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'

]

[

'timestamp'

]

.

iloc

[

0

]

)

.

dt

.

days

print

(

df

)

Result:



=== 时间戳比较 ===

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:


Notes

Important note:

  • pd.Timestamp It is similar to Python's datetime but offers higher performance and more methods.
  • Timestamp objects are immutable; modification operations return a new object.
  • It is best to specify timezone information at creation time; changing the timezone later may cause ambiguity.
  • Use pd.NaT(Not a Time) represents a missing time value.

  • Pandas Universal Functions Common Pandas functions