Pandas: Create a timestamp

30 July 2020

Code

# Import library
import pandas as pd

Option # 1: Using ‘pd.Timestamp()’ with year, month etc.

# Using 'Timestamp' with year, month etc.
t1 = pd.Timestamp(year=2020, month=7, day=30)
t2 = pd.Timestamp(year=2020, month=7, day=30, hour=21, minute=30, second=20, microsecond=888, nanosecond=999, tz='UTC')

# Output
print('Without timezone: \n',t1)
print('With UTC: \n', t2)

Output

Without timezone: 
 2020-07-30 00:00:00
With UTC: 
 2020-07-30 21:30:20.000888999+00:00



Option # 2: Using ‘Timestamp’ with nanoseconds

# Using 'Timestamp' with nanoseconds
t = pd.Timestamp(ts_input=1596144620000000000, unit='ns')

# Output
print(t)

Output

2020-07-30 21:30:20



Option # 3: Using ‘pd.to_datetime()’ with string

# Using 'to_datetime' with string
t = pd.to_datetime('2020-07-30 21:30:20', format='%Y-%m-%d %H:%M:%S')

# Output
print(t)

Output

2020-07-30 21:30:20



Option # 4: Using ‘to_datetime()’ with nanosecond

# Using 'to_datetime' with nanosecond
t = pd.to_datetime(arg=1596144620000000000, unit='ns')

# Output
print(t)

Output

2020-07-30 21:30:20






Any errors in code above?
Please send a message.