python - python中字符串的算术[MINUS]

标签 python

我有一个字符串,它基本上是一个 CSV 文件的标题,我必须从中提取月份,然后通过在它前面附加一个“0”来将其转换为字符串以与其他值进行比较。

标题--

HGLOABCD8PSGL_ZXFH J20190603NXT_APAC

由此我需要从 20190603 中提取月份,即 06,然后创建一个列表,如 ['006', '005'] 列表的第二个元素将是标题中给定月份的前一个月

标题也可以像月份不同的地方

HGLOABCD8PSGL_ZXFH J20191003NXT_APAC

我已经为第一个元素写了类似这样的内容,但不确定如何减去一个月然后向其附加“0”。

acc_period = []
acc_period.append('0'+str(header)[26:28])

acc_period.append(int('0') + int(str(header)[26:28])-1)
print (acc_period)

最佳答案

使用正则表达式。

例如:

import re
from datetime import datetime, timedelta
data = ['HGLOABCD8PSGL_ZXFH J20190603NXT_APAC', 'HGLOABCD8PSGL_ZXFH J20191003NXT_APAC', 'HGLOABCD8PSGL_ZXFH J20190103NXT_APAC']

def a_day_in_previous_month(dt):   #https://stackoverflow.com/a/7153449/532312
    return (dt.replace(day=1) - timedelta(days=1)).month

for i in data:
    m = re.search(r"(\d{8,})", i)
    if m:
        date = datetime.strptime(m.group(0), "%Y%m%d")
        print("{}".format(date.month).zfill(3), "{}".format(a_day_in_previous_month(date)).zfill(3))

输出:

006 005
010 009
001 012

关于python - python中字符串的算术[MINUS],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58911545/

相关文章:

python - 索引错误 : tuple index out of range postgresql

python - 快速找到最接近某个值的数组中的索引

python - 从计数表计算相对频率

python - 根据单列删除 CSV 文件的重复行

python - 如何避免浮点错误?

python - GNS3 错误 : WaitForConnectionWorker thread stopping with an error: Could not connect to 127. 0.0.1 在端口 3090 上:[Errno 111] Conexión rehusada

python - 面向对象编程 - 访问另一个类的名称

python - 将我的 django 应用程序连接到 redis 安装

python - 使用相同库的多个 AWS Lambda 函数

python - 同时过滤两个列表