Pandas Convert Column as Datetime/Timestamp (String, Epoch Seconds)

February 24, 2021

Date String

import pandas as pd 

items = [
  {'date': '2020-01-01', 'score': 1},
  {'date': '2020-01-01', 'score': 2},
  {'date': '2020-01-01', 'score': 3}
]

df = pd.DataFrame(items) 
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
        date  score
0 2022-01-01      1
1 2022-01-02      2
2 2022-01-03      3

Epoch Seconds

import pandas as pd 

items = [
  {'date': '1640995200', 'score': 1},
  {'date': '1641081600', 'score': 2},
  {'date': '1641168000', 'score': 3}
]

df = pd.DataFrame(items) 
df['date'] = pd.to_datetime(df['date'], unit="s")
        date  score
0 2022-01-01      1
1 2022-01-02      2
2 2022-01-03      3

Epoch Milliseconds

import pandas as pd 

items = [
  {'date': '1640995200000', 'score': 1},
  {'date': '1641081600000', 'score': 2},
  {'date': '1641168000000', 'score': 3}
]

df = pd.DataFrame(items) 
df['date'] = pd.to_datetime(df['date'], unit="ms")
        date  score
0 2022-01-01      1
1 2022-01-02      2
2 2022-01-03      3

Datetime

import datetime
import pandas as pd

items = [
  {'date': datetime.datetime(2020, 1, 1), 'score': 1},
  {'date': datetime.datetime(2020, 1, 2), 'score': 2},
  {'date': datetime.datetime(2020, 1, 3), 'score': 3}
]

df = pd.DataFrame(items) 
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.