简体   繁体   English

如何在python中将203045格式化为以下时间:

[英]How do you add : to a time formatted like this 203045 in python?

I've been trying to get this time formatted value from 203045 to 20:40:45 in python. 我一直试图在python中将此时间格式的值从203045更改为20:40:45。 I clearly have no clue where to start. 我显然不知道从哪里开始。 Any help will be appreciated! 任何帮助将不胜感激! Thanks! 谢谢!

Use strptime and strftime functions from datetime , the former constructs a datetime object from string and the latter format datetime object to string with specific format: 使用datetime strptimestrftime函数,前者从字符串构造一个datetime对象,后者将datetime对象格式化为具有特定格式的字符串:

from datetime import datetime
datetime.strptime("203045", "%H%M%S").strftime("%H:%M:%S")
# '20:30:45'

you can also play with the regular expression to get the same result :) 您还可以使用正则表达式获得相同的结果:)

import re
ch = "203045"
print ":".join(re.findall('\d{2}',ch))
# '20:30:45'

try this to remove the two last digits if they are equal to zero : 尝试此操作以删除最后两个数字(如果它们等于零):

import re
ch = "20304500"
print ":".join([e for e in re.findall('\d{2}',ch) if e!="00"])
# '20:30:45'

or whatever (the two last digits) : 或其他任何数字(最后两位):

import re
ch = "20304500"
print ":".join(re.findall('\d{2}',ch)[:-1])
# '20:30:45'

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

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