如何在Python中将字符串转换为timetuple

时间:2018-01-30 08:07:14

标签: python python-3.x

假设我有一个Dataframe:

df = {'date':['20170101', '20170102', '20170103', '20170104']}

我想将'20170101'转换为'2017-01-01 00:00:00'

我怎样才能实现它?

3 个答案:

答案 0 :(得分:4)

您可以将日期时间字符串转换为jump对象。然后得到你想要的任何格式:

datetime

输出:

from datetime import datetime

datetime.strptime("20170103", "%Y%m%d").strftime("%Y-%m-%d %H:%M:%S")

答案 1 :(得分:3)

如果你有@SuppressWarnings("unchecked") @Override public void onApplicationEvent(ApplicationReadyEvent arg0) { ECServiceFactory svcFactory = new ECServiceFactory(application, documentService,new SuperUser(),AccessDeniedException.class,config); } ,你可以用:

代码:

pandas.DataFrame

测试代码:

pd.to_datetime(df['date'], format='%Y%m%d')

结果:

df = pd.DataFrame({'date':['20170101', '20170102', '20170103', '20170104']})
df['date2'] = df['date'].apply(lambda d: dt.datetime.strptime(d, '%Y%m%d'))
df['date3'] = pd.to_datetime(df['date'], format='%Y%m%d')
print(df)

答案 2 :(得分:0)

如果你知道如何构建字符串(即YYYYMMDD),你可以简单地使用它:

def f(s):
    return '{}-{}-{} 00:00:00'.format(s[:4],s[4:6],s[6:])
s = '20170101'

f(s)
Out[7]: '2017-01-01 00:00:00'