1

using python 3.8, pandas 1.14

I have an integer value 20210126

I want to create an datetime object and str object of it.

current method:

dt = 20210126
dt_dt = datetime(year=d_i//10000, month=(d_i%10000)//100, day=d_i%100)
str_dt = dt_dt.strftime("%Y%m%d")

Alternative:

dt = 20210126
dt_dt = datetime(year=int(str(d_i)[:3]), month=int(str(d_i)[3:5]), day= int(str(d_i)[5:])
str_dt = str(dt)

This works fine however wondering if there is convient way.

haneulkim
  • 4,406
  • 9
  • 38
  • 80
  • Does this answer your question? [Convert Pandas Column to DateTime](https://stackoverflow.com/questions/26763344/convert-pandas-column-to-datetime) – ti7 Feb 04 '21 at 03:12
  • 1
    @ti7 Not quite, after some tweaks yes however answer below is more intuitive for Non-pandas uses also so I prefer leaving it, – haneulkim Feb 04 '21 at 03:32

2 Answers2

2

Use strptime and strftime

value = 20210126
d = datetime.datetime.strptime(str(value), "%Y%m%d")
# datetime.datetime(2021, 1, 26, 0, 0)
d.strftime("%a, %b %m, '%y")
# "Tue, Jan 01, '21"

Format codes listed here!: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

If you are working within Pandas, it may actually be easier to keep these as some simple integer type until you need them, but you can convert the values similarly with its .to_datetime() method

import pandas as pd
df = pd.DataFrame({"dates": [20010101, 20020202]})
#       dates
# 0  20010101
# 1  20020202
pd.to_datetime(df.dates, format="%Y%m%d")
# 0   2001-01-01
# 1   2002-02-02
# Name: dates, dtype: datetime64[ns]

These can also then be represented as strings of some form by using the .dt.strftime method of the Series
Note .dt is from the df.dates column in this case and is a special accessor for datetime Series

df.dates = pd.to_datetime(df.dates, format="%Y%m%d")
#        dates
# 0 2001-01-01
# 1 2002-02-02
df.dates.dt.strftime("%a, %b %m, '%y")
# 0    Mon, Jan 01, '01
# 1    Sat, Feb 02, '02
# Name: dates, dtype: object
ti7
  • 16,375
  • 6
  • 40
  • 68
1

You can use strptime():

import time

dt = 20210126
str_dt = str(dt)
dt_dt = time.strptime(str_dt, '%Y%m%d')
Kien Nguyen
  • 2,616
  • 2
  • 7
  • 24