将int(yyyymmdd)转换为datetime对象和str的简便方法 [英] Convient way to convert int(yyyymmdd) to datetime object and str
问题描述
使用python 3.8,pandas 1.14
using python 3.8, pandas 1.14
我的整数值为20210126
I have an integer value 20210126
我想创建一个日期时间对象和它的str对象.
I want to create an datetime object and str object of it.
当前方法:
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")
替代:
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.
推荐答案
使用 strptime
和 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"
此处列出格式代码!: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
Format codes listed here!: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
如果您在Pandas中工作,将它们保留为简单的整数类型实际上可能会更容易,直到需要它们为止,但是您可以使用其
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]
然后,也可以使用 .dt.strftime
方法将这些字符串表示为某种形式的字符串系列
注意 .dt
在这种情况下来自 df.dates
列,并且是
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
这篇关于将int(yyyymmdd)转换为datetime对象和str的简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!