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

Feb 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 datetimeimport pandas as pditems = [  {'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) 

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.