尽管注释中不鼓励使用regex,但可以使用regex将时间对象解析为datetime.time对象,对它们执行必要的计算,然后以所需格式打印它们:# datetime module for time calculations

import datetime

# regex module

import re

# seconds to add to time

myinp = 4

# List of data strings

# data = 'John Time Made 11:05:20 in 2010', '5.001 Kelly', '6.005 Josh'

with open('data.txt') as f:

data = f.readlines()

new_data = []

#iterate through the list of data strings

for time in data:

try:

# First check for 'HH:MM:SS' time format in data string

# regex taken from this question: http://stackoverflow.com/questions/8318236/regex-pattern-for-hhmmss-time-string

match = re.findall("([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)", time)

# this regex returns a list of tuples as strings "[('HH', 'MM', 'SS')]",

# which we join back together with ':' (colon) separators

t = ':'.join(match[0])

# create a Datetime object from indexing the first matched time in the list,

# taken from this answer http://stackoverflow.com/questions/100210/what-is-the-standard-way-to-add-n-seconds-to-datetime-time-in-python

# May create an IndexError exception, which we catch in the `except` clause below

orig = datetime.datetime(100,1,1,int(match[0][0]), int(match[0][1]), int(match[0][2]))

# Add the number of seconds to the Datetime object,

# taken from this answer: http://stackoverflow.com/questions/656297/python-time-timedelta-equivalent

newtime = (orig + datetime.timedelta(0, myinp)).time()

# replace the time in the original data string with the newtime and print

new_data.append(time.replace(t, str(newtime)))

# catch an IndexError Exception, which we look for float-formatted seconds only

except IndexError:

# look for float-formatted seconds (s.xxx)

# taken from this answer: http://stackoverflow.com/questions/4703390/how-to-extract-a-floating-number-from-a-string

match = re.findall("\d+\.\d+", time)

# create a Datetime object from indexing the first matched time in the list,

# specifying only seconds, and microseconds, which we convert to milliseconds (micro*1000)

orig = datetime.datetime(100,1,1,second=int(match[0].split('.')[0]),microsecond=int(match[0].split('.')[1])*1000)

# Subtract the seconds from the Datetime object, similiar to the time addtion in the `try` clause above

newtime = orig - datetime.timedelta(0, myinp)

# format the newtime as `seconds` concatenated with the milliseconds converted from microseconds

newtime_fmt = newtime.second + newtime.microsecond/1000000.

# Get the seconds value (first value(index 0)) from splitting the original string at the `space` between the `seconds` and `name` strings

t = time.split(' ')[0]

# replace the time in the original data string with the newtime and print

new_data.append(time.replace(t , str(newtime_fmt)))

with open('new_data.txt', 'w') as nf:

for newline in new_data:

nf.write(newline)

new_data.txt文件内容应为:

^{pr2}$

python输入一个字符一个数字_Python:如何只对字符串中的数字字符加/减一个数字?...相关推荐

  1. 组数(【问题描述】输入一行字符串(设字符数不大于80),提取该字符串中的数字字符并组成一个整数,输出该整数及其两倍的值。)

    组数 [问题描述]输入一行字符串(设字符数不大于80),提取该字符串中的数字字符并组成一个整数,输出该整数及其两倍的值.要求在主函数中输入字符串,并输出结果.在子函数中提取该字符串中的数字字符并组成一 ...

  2. 输入英文字符,请按照字母表顺序统计字符串中所有出现的字母的个数

    字符统计 描述 输入英文字符,请按照字母表顺序统计字符串中所有出现的字母的个数(计数时不区分大小写),若输入的内容有误,则输出Error! 输入 一串字符. 输出 按题目要求输出. 输入样例 1 He ...

  3. 将字符串中的数字字符转换为对应的数字,并且求和输出

    问题描述 用一个函数fun将字符串中的数字字符转换为对应的数字,计算出这些数值的累计和,然后作为函数值返回. 例如:形参s的字符串为:I have 66 dollars.输出结果为12. 程序代码 # ...

  4. java 字符串 数字个数_Java简单统计字符串中汉字,英文字母及数字数量的方法...

    本文实例讲述了Java简单统计字符串中汉字,英文字母及数字数量的方法.分享给大家供大家参考,具体如下: package org.zhy.demo.algorithm; /** * 有一个字符串,其中包 ...

  5. python 如何定义一个变量为数字_python – 如何在Pandas / Numpy中确定列/变量是否为数字?...

    您也可以使用带有np.number的 np.issubdtype.考虑下面的DataFrame: df = pd.DataFrame({'A': [1, 2, 3], 'B': [1.0, 2.0, ...

  6. python里边的单词都表示什么_Python:只保留字符串中的单词,每个单词都在newlin上...

    您可以不使用正则表达式来执行此操作.拆分管道字符上的字符串,使用生成器表达式和inbuild string.isalpha()函数筛选出仅为字母字符的单词,并将它们连接起来以形成最终输出:old_fr ...

  7. c语言学习-对从键盘输入的一个字符串中的大英字母及数字进行计数

    对从键盘输入的一个字符串中的大英字母及数字进行计数 程序流程图: 代码: #include<stdio.h> void main() {char ch[10]; int i=0,j=0; ...

  8. python统计中文字符的个数_python统计中文字符数量的两种方法

    方法一: def str_count(str): '''找出字符串中的中英文.空格.数字.标点符号个数''' count_en = count_dg = count_sp = count_zh = c ...

  9. c语言中减号算一个字符吗,C语言中指针的加减运算

    char arr[3]; printf("arr:\n%d\n%d\n%d\n", arr, arr + 1, arr + 2); char *parr[3]; printf(&q ...

最新文章

  1. Spring Cloud之Hystrix
  2. mysql 集群切换_完美起航-MySQLMHA高可用集群部署及故障切换(图文详解)
  3. 压缩版styleGAN
  4. java 输出三位数和n位数的每一位的数
  5. HDU2087 剪花布条【KMP】
  6. Web服务中延时对QoE(体验质量)的影响
  7. 【DEBUG】undefined reference to `cv_bridge::toCvShare
  8. SWFUpload flash上传控件
  9. eclipse 远程链接访问hadoop 集群日志信息没有输出的问题l
  10. Java编写的日历,输入年月,输出这个月的日期与星期
  11. EST 云硬盘修复小工具-SAS希捷固件升级工具
  12. 安卓屏幕朗读app_android录屏app推荐?安卓手机屏幕录制方法步骤教程
  13. c语言中空格的转义字符是什么意思,转义字符-转义字符是什么意思? 爱问知识人...
  14. C# AES填充加密解密
  15. submit的form表单提交事件
  16. 数商云:大宗商品撮合交易平台搭建丨加强业务、技术、应用与集成的创新
  17. 什么是V2X?如何通过V2X技术实现5G智慧交通?
  18. 由浅至深探探webpack(初)
  19. DataView RowFilter
  20. 计算机工资高的岗位,毕业五年后工资最高的4大专业,就业容易岗位多

热门文章

  1. MS SQL SERVER数据库简单回顾
  2. 从源码角度分析下 micrometer 自定义 metrics endpoint 和 springboot actuator
  3. MySQL操作权限整理
  4. Spring事务管理详解_基本原理_事务管理方式
  5. Ant Design Pro 2.0/umijs站点配置到非站点根目录下处理
  6. Oracle DMP 导入导出
  7. wmode解决flash透明及层深问题
  8. Android M 新的运行时权限开发者需要知道的一切
  9. 【C语言进阶深度学习记录】二十一 # 和 ## 号操作符的使用与分析
  10. [给ASP.NET 初学者的话]不要练功练了三年,才发现自己必须「砍掉重练」!....学习ASP.NET之前,请先把自己杯中的水倒掉...