简体   繁体   English

Python日期时间格式-字符串为指定格式

[英]Python date time formatting - String to a specified format

I am looking to convert raw string to a specified data time format. 我想将原始字符串转换为指定的数据时间格式。

Here's the sample data: 这是示例数据:

0              47 mins
1       1 hour 25 mins
2       1 hour 27 mins
3               6 mins

Is the above one of the supported date time formats in python that can be transformed using some function - to_datetime or strftime? 上面是python中支持的日期时间格式之一,可以使用某些函数-to_datetime或strftime转换吗? or would this need to handled/parsed out differently. 还是需要以不同的方式处理/解析。

Expected format: 预期格式:

00:47
01:25
01:27
00:06

You have 2 potential formats, so you can try them each: 您有2种可能的格式,因此可以分别尝试:

s = pd.Series(['47 mins', '1 hour 25 mins', '1 hour 27 mins', '6 mins'])

dt1 = pd.to_datetime(s, format='%H hour %M mins', errors='coerce')
dt2 = pd.to_datetime(s, format='%M mins', errors='coerce')

res = dt1.fillna(dt2).dt.strftime('%H:%M')

print(res)

0    00:47
1    01:25
2    01:27
3    00:06
dtype: object

You can convert some keywords to appropriate things to be passed to pandas.Timedelta 您可以将一些关键字转换为适当的内容以传递给pandas.Timedelta

d = {'mins': 'minutes', 'secs': 'seconds', 'hour': 'hours'}
td = [
    pd.Timedelta(**dict(zip(s[1::2], map(float, s[::2]))))
    for s in [s.split() for s in s.replace(d, regex=True)]
]

pd.Series(td, s.index)

0   00:47:00
1   01:25:00
2   01:27:00
3   00:06:00
dtype: timedelta64[ns]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM