解析和重写日期时间字符串

2024-04-26 14:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个时间数据字符串:“2019-08-0218:18:06.02887”,我正试图在另一个文件中将其重写为另一个字符串“EV190802_181802”

我现在尝试的是将字符串拆分为列表,并通过这些列表重建另一个字符串:

hello=data.split(' ')
date=hello[0]
time=hello[1]
world=hello[0].split('-')
stack=time.split('.')
overflow=stack[0].split(':')
print('EV' + world[0] + world[1] + world[2] + '_' + overflow[0] + overflow[1] + overflow[2])

但是,我不知道如何在2019/world[0]中删除20个。有没有办法删除“20”

如果有其他方法重写字符串,也欢迎提出建议


Tags: 文件数据字符串hello列表worlddatatime
3条回答

使用正则表达式:

import re

data = "2019-08-02 18:18:06.02887"
res = re.match(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})\s(?P<hours>\d{2}):(?P<minutes>\d{2}):(?P<seconds>\d{2}).(?P<miliseconds>\d+)',data)

out = f"EV{res.group('year')[2:]}{res.group('month')}{res.group('day')}_{res.group('hours')}{res.group('minutes')}{res.group('miliseconds')[:2]}"
print(out) 

输出将是:

EV190802_181802

这只是解决问题的另一种方法

>>> from datetime import datetime
>>> 
>>> format_ = datetime.strptime("2019-08-02 18:18:06.02887", 
...                             "%Y-%m-%d %H:%M:%S.%f")
>>> 
>>> print(
    format_.strftime('EV%y%m%d_%H%M') + format_.strftime('%f')[:2]
)

EV190802_181802
  1. 删除所有出现的-.:

     hello.replace("-","")
     hello.replace(".","")
     hello.replace(":","")
    
  2. 在一行中获取字符串:

     print("EV" + hello[2:8] + "_" + hello[9:15])
    

相关问题 更多 >