YouTip LogoYouTip

Pandas Pd Timestamp

Pandas pd.Timestamp() Function |\n\n

Image 1: Pandas Universal Functions Pandas Common Functions

\n\n
\n\n

pd.Timestamp() is a function in the Pandas library used to create timestamps. It can accept various date-time input formats and return an accurate Timestamp object.

\n\n

A 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, offering richer functionality and better performance.

\n\n

Word Definition: Timestamp means "timestamp", which represents a specific moment.

\n\n
\n\n

Basic Syntax and Parameters

\n\n

pd.Timestamp() is a top-level function in the Pandas library for creating precise timestamp objects.

\n\n

Syntax Format

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

Parameter Description

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ParameterTypeRequiredDescriptionDefault
valuestring, datetime, int, floatOptionalThe time value to be converted.None
yearintegerOptionalYear (4-digit number).None
monthintegerOptionalMonth (1-12).None
dayintegerOptionalDay (1-31).None
hourintegerOptionalHour (0-23).None
minuteintegerOptionalMinute (0-59).None
secondintegerOptionalSecond (0-59).None
microsecondintegerOptionalMicrosecond (0-999999).None
nanosecondintegerOptionalNanosecond (0-999999).None
tzstring or tzinfoOptionalTime zone information such as 'UTC', 'Asia/Shanghai'.None
\n\n

Return Value Description

\n\n
    \n
  • Return Value: Returns a Timestamp object, similar to datetime.datetime.
  • \n
  • Effect: Converts various time data formats into precise Pandas timestamps.
  • \n
\n\n
\n\n

Examples

\n\n

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

\n\n

Example 1: Basic Usage - Creating Timestamps

\n\n

Example

\n\n
import pandas as pd\n\n# 1. Create timestamps using strings\n\nprint("=== String-based Timestamp Creation ===")\n\nts1 = pd.Timestamp('2023-01-01')\n\nprint(f"pd.Timestamp('2023-01-01'): {ts1}")\n\nts2 = pd.Timestamp('2023-01-01 12:30:45')\n\nprint(f"pd.Timestamp('2023-01-01 12:30:45'): {ts2}")\n\nts3 = pd.Timestamp('2023-05-15 08:00:00.123456')\n\nprint(f"With microseconds: {ts3}")\n\n# 2. Create timestamps using keyword arguments\n\nprint("n=== Keyword Arguments Creation ===")\n\nts4 = pd.Timestamp(year=2023, month=6, day=15, hour=10, minute=30)\n\nprint(f"pd.Timestamp(year=2023, month=6, day=15, hour=10, minute=30): {ts4}")\n\n# 3. Create from datetime object\n\nprint("n=== From datetime Object ===")\n\nimport datetime\n\ndt = datetime.datetime(2023,8,20,14,45,30)\n\nts5 = pd.Timestamp(dt)\n\nprint(f"From datetime: {ts5}")\n\n# 4. View timestamp attributes\n\nprint("n=== Timestamp Attributes ===")\n\nts = pd.Timestamp('2023-03-15 10:30:45.123456')\n\nprint(f"Timestamp: {ts}")\n\nprint(f"Year: {ts.year}")\n\nprint(f"Month: {ts.month}")\n\nprint(f"Day: {ts.day}")\n\nprint(f"Hour: {ts.hour}")\n\nprint(f"Minute: {ts.minute}")\n\nprint(f"Second: {ts.second}")\n\nprint(f"Microsecond: {ts.microsecond}")\n\nprint(f"Weekday (0=Monday): {ts.dayofweek}")\n\nprint(f"Quarter: {ts.quarter}")\n
\n\n

Output:

\n\n
=== String-based Timestamp Creation ===\npd.Timestamp('2023-01-01'): 2023-01-01 00:00:00\npd.Timestamp('2023-01-01 12:30:45'): 2023-01-01 12:30:45\nWith microseconds: 2023-05-15 08:00:00.123456\n=== Keyword Arguments Creation ===\npd.Timestamp(year=2023, month=6, day=15, hour=10, minute=30): 2023-06-15 10:30:00\n=== From datetime Object ===\nFrom datetime: 2023-08-20 14:45:30\n=== Timestamp Attributes ===\nTimestamp: 2023-03-15 10:30:45.123456\nYear: 2023\nMonth: 3\nDay: 15\nHour: 10\nMinute: 30\nSecond: 45\nMicrosecond: 123456\nWeekday (0=Monday): 2\nQuarter: 1\n
\n\n

Code Explanation:

\n\n
    \n
  1. pd.Timestamp() accepts multiple input formats including strings and datetime objects.
  2. \n
  3. Timestamps provide rich attributes for accessing different parts of the date-time.
  4. \n
  5. dayofweek returns 0-6 where 0 indicates Monday.
  6. \n
\n\n

Example 2: Timezone Handling

\n\n

Example

\n\n
import pandas as pd\n\n# 1. Create timestamps with timezone\n\nprint("=== Creating Timestamps with Timezone ===")\n\nts_utc = pd.Timestamp('2023-01-01 12:00:00', tz='UTC')\n\nprint(f"UTC timezone: {ts_utc}")\n\nts_shanghai = pd.Timestamp('2023-01-01 20:00:00', tz='Asia/Shanghai')\n\nprint(f"Shanghai timezone: {ts_shanghai}")\n\n# 2. Convert between timezones\n\nprint("n=== Timezone Conversion ===")\n\nts_utc = pd.Timestamp('2023-01-01 12:00:00', tz='UTC')\n\nts_local = ts_utc.tz_convert('Asia/Shanghai')\n\nprint(f"UTC time: {ts_utc}")\n\nprint(f"Converted to Shanghai: {ts_local}")\n\n# 3. Local timestamp to timezone-aware\n\nprint("n=== Local Time to Timezone-aware ===")\n\nts_naive = pd.Timestamp('2023-01-01 12:00:00')\n\nprint(f"No timezone: {ts_naive}")\n\nts_aware = ts_naive.tz_localize('Asia/Shanghai')\n\nprint(f"Added Shanghai timezone: {ts_aware}")\n\n# 4. Short form using tz parameter\n\nprint("n=== Timezone Abbreviations ===")\n\nts1 = pd.Timestamp('2023-01-01 12:00', tz='US/Eastern')\n\nprint(f"US Eastern: {ts1}")\n\nts2 = pd.Timestamp('2023-01-01 12:00', tz='Europe/London')\n\nprint(f"London: {ts2}")\n
\n\n

Output:

\n\n
=== Creating Timestamps with Timezone ===\nUTC timezone: 2023-01-01 12:00:00+00:00\nShanghai timezone: 2023-01-01 20:00:00+08:00\n=== Timezone Conversion ===\nUTC time: 2023-01-01 12:00:00+00:00\nConverted to Shanghai: 2023-01-01 20:00:00+08:00\n=== Local Time to Timezone-aware ===\nNo timezone: 2023-01-01 12:00:00\nAdded Shanghai timezone: 2023-01-01 12:00:00+08:00\n=== Timezone Abbreviations ===\nUS Eastern: 2023-01-01 12:00:00-05:00\nLondon: 2023-01-01 12:00:00+00:00\n
\n\n

Code Explanation:

\n\n
    \n
  • tz_localize adds timezone info to a naive timestamp.
  • \n
  • tz_convert converts between different timezones.
  • \n
\n\n

Example 3: Comparison and Operations on Timestamps

\n\n

Example

\n\n
import pandas as pd\n\n# 1. Compare timestamps\n\nprint("=== Timestamp Comparison ===")\n\nts1 = pd.Timestamp('2023-01-01')\n\nts2 = pd.Timestamp('2023-01-15')\n\nts3 = pd.Timestamp('2023-01-01')\n\nprint(f"ts1: {ts1}")\n\nprint(f"ts2: {ts2}")\n\nprint(f"ts1 < ts2: {ts1 < ts2}")\n\nprint(f"ts1 == ts3: {ts1 == ts3}")\n\nprint(f"ts1 != ts2: {ts1 != ts2}")\n\n# 2. Timestamp and Timedelta operations\n\nprint("n=== Timestamp and Timedelta Operations ===")\n\nts = pd.Timestamp('2023-01-01 12:00:00')\n\ntd = pd.Timedelta(days=5, hours=3)\n\nprint(f"Original timestamp: {ts}")\n\nprint(f"Timedelta: {td}")\n\nprint(f"ts + td: {ts + td}")\n\nprint(f"ts - td: {ts - td}")\n\n# 3. Subtract two timestamps to get Timedelta\n\nprint("n=== Subtracting Two Timestamps ===")\n\nts1 = pd.Timestamp('2023-01-15 18:00:00')\n\nts2 = pd.Timestamp('2023-01-10 09:00:00')\n\ndiff = ts1 - ts2\n\nprint(f"ts1: {ts1}")\n\nprint(f"ts2: {ts2}")\n\nprint(f"ts1 - ts2: {diff}")\n\nprint(f"Days: {diff.days}")\n\nprint(f"Hours: {diff.seconds / 3600}")\n\n# 4. Use timestamps in DataFrame\n\nprint("n=== Timestamps in DataFrame ===")\n\ndf = pd.DataFrame({\n    'event': ['event_a','event_b','event_c'],\n    'timestamp': [\n        pd.Timestamp('2023-01-01 10:00:00'),\n        pd.Timestamp('2023-01-02 15:30:00'),\n        pd.Timestamp('2023-01-03 09:45:00')\n    ]\n})\n\nprint(df)\n\nprint(f"nEvent durations (relative to first event):")\ndf['relative_days']=(df['timestamp'] - df['timestamp'].iloc).dt.days\nprint(df)\n
\n\n

Output:

\n\n
=== Timestamp Comparison ===\nts1: 2023-01-01 00:00:00\nts2: 2023-01-15 00:00:00\nts1 < ts2: True\nts1 == ts3: True\nts1 != ts2: True\n=== Timestamp and Timedelta Operations ===\nOriginal timestamp: 2023-01-01 12:00:00\nTimedelta: 5 days 03:00:00\nts + td: 2023-01-06 15:00:00\nts - td: 2022-12-27 09:00:00\n=== Subtracting Two Timestamps ===\nts1: 2023-01-15 18:00:00\nts2: 2023-01-10 09:00:00\nts1 - ts2: 5 days 09:00:00\nDays: 5\nHours: 9.0\n=== Timestamps in DataFrame ===\n    event           timestamp\n0  event_a 2023-01-01 10:00:00\n1  event_b 2023-01-02 15:30:00\n2  event_c 2023-01-03 09:45:00\n\nEvent durations (relative to first event):\n    event           timestamp  relative_days\n0  event_a 2023-01-01 10:00:00              0\n1  event_b 2023-01-02 15:30:00              1\n2  event_c 2023-01-03 09:45:00              2\n
\n\n

Code Explanation:

\n\n
    \n
  • Timestamps support direct comparison operators (<, ==, !=).
  • \n
  • Adding or subtracting a Timedelta from a timestamp results in a new timestamp or timedelta.
  • \n
  • Subtracting two timestamps gives a Timedelta object.
  • \n
  • DataFrames allow convenient time-related calculations.
  • \n
\n\n
\n\n

Notes

\n\n
\n

Important Notes:

\n\n
    \n
  • pd.Timestamp is similar to Python's datetime but offers higher performance and more methods.
  • \n
  • Timestamp objects are immutable; modification operations return new objects.
  • \n
  • It's best to specify timezone information during creation; modifying it later may cause ambiguity.
  • \n
  • Use pd.NaT (Not a Time) to represent missing time values.
  • \n
\n
\n\n
\n\n

Image 2: Pandas Universal Functions Pandas Common Functions

← Pandas Series Dt YearPandas Series Str Len β†’