标签归档:format

Python TypeError:格式字符串的参数不足

问题:Python TypeError:格式字符串的参数不足

这是输出。我相信这些是utf-8字符串…其中一些可以是NoneType,但是在类似这样的字符串之前会立即失败…

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname, procversion, int(percent), exe, description, company, procurl

TypeError:格式字符串的参数不足

虽然是7比7?

Here’s the output. These are utf-8 strings I believe… some of these can be NoneType but it fails immediately, before ones like that…

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname, procversion, int(percent), exe, description, company, procurl

TypeError: not enough arguments for format string

Its 7 for 7 though?


回答 0

请注意,%格式化字符串的语法已过时。如果您的Python版本支持它,则应编写:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

这也可以修复您碰巧遇到的错误。

Note that the % syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

This also fixes the error that you happened to have.


回答 1

您需要将格式参数放入元组(添加括号):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

您当前拥有的等同于以下内容:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

例:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

回答 2

%在格式字符串中用作百分比字符时,出现了相同的错误。解决的办法是加倍%%

I got the same error when using % as a percent character in my format string. The solution to this is to double up the %%.


格式化字符串时多次插入相同的值

问题:格式化字符串时多次插入相同的值

我有这种形式的字符串

s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)

字符串中的所有%s都具有相同的值(即s)。有没有更好的书写方式?(而不是列出三遍)

I have a string of this form

s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)

All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)


回答 0

您可以使用Python 2.6和Python 3.x中提供的高级字符串格式

incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

You can use advanced string formatting, available in Python 2.6 and Python 3.x:

incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

回答 1

incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}

您可能需要阅读以下内容以了解:String Formatting Operations

incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}

You may like to have a read of this to get an understanding: String Formatting Operations.


回答 2

您可以使用格式的字典类型:

s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}

You can use the dictionary type of formatting:

s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}

回答 3

取决于您的意思更好。如果您的目标是消除冗余,则此方法有效。

s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))

Depends on what you mean by better. This works if your goal is removal of redundancy.

s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))

回答 4

>>> s1 ='arbit'
>>> s2 = 'hello world '.join( [s]*3 )
>>> print s2
arbit hello world arbit hello world arbit
>>> s1 ='arbit'
>>> s2 = 'hello world '.join( [s]*3 )
>>> print s2
arbit hello world arbit hello world arbit

回答 5

弦线

如果您正在使用Python 3.6+,则可以使用新的,f-strings它代表格式化的字符串,可以通过f在字符串的开头添加字符以将其标识为f字符串来使用它

price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!

使用f字符串的主要好处是它们更具可读性,可以更快,并且具有更好的性能:

每个人的熊猫资源:Python数据分析,作者Daniel Y. Chen

基准测试

毫无疑问,新f-strings方法更具可读性,因为您不必重新映射字符串,但是如前所述,它是否更快?

price = 123
name = "Jerry"

def new():
    x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"


def old():
    x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)

import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776  #new
> 5.861819514350163   #old

运行1000万次测试似乎新f-strings的映射速度实际上更快。

Fstrings

If you are using Python 3.6+ you can make use of the new so called f-strings which stands for formatted strings and it can be used by adding the character f at the beginning of a string to identify this as an f-string.

price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!

The main benefits of using f-strings is that they are more readable, can be faster, and offer better performance:

Source Pandas for Everyone: Python Data Analysis, By Daniel Y. Chen

Benchmarks

No doubt that the new f-strings are more readable, as you don’t have to remap the strings, but is it faster though as stated in the aformentioned quote?

price = 123
name = "Jerry"

def new():
    x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"


def old():
    x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)

import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776  #new
> 5.861819514350163   #old

Running 10 Million test’s it seems that the new f-strings are actually faster in mapping.


如何以固定宽度打印字符串?

问题:如何以固定宽度打印字符串?

我有这段代码(在字符串中打印所有排列的出现)

def splitter(str):
    for i in range(1, len(str)):
        start = str[0:i]
        end = str[i:]
        yield (start, end)
        for split in splitter(end):
            result = [start]
            result.extend(split)
            yield result    

el =[];

string = "abcd"
for b in splitter("abcd"):
    el.extend(b);

unique =  sorted(set(el));

for prefix in unique:
    if prefix != "":
        print "value  " , prefix  , "- num of occurrences =   " , string.count(str(prefix));

我想打印字符串可变项中所有出现的排列。

由于排列的长度不同,所以我想固定宽度并以一种不太好的方式打印它:

value   a - num of occurrences =    1
value   ab - num of occurrences =    1
value   abc - num of occurrences =    1
value   b - num of occurrences =    1
value   bc - num of occurrences =    1
value   bcd - num of occurrences =    1
value   c - num of occurrences =    1
value   cd - num of occurrences =    1
value   d - num of occurrences =    1

我该如何使用format呢?

我找到了这些帖子,但与字母数字字符串的配合并不理想:

python字符串格式固定宽度

使用python设置固定长度

I have this code (printing the occurrence of the all permutations in a string)

def splitter(str):
    for i in range(1, len(str)):
        start = str[0:i]
        end = str[i:]
        yield (start, end)
        for split in splitter(end):
            result = [start]
            result.extend(split)
            yield result    

el =[];

string = "abcd"
for b in splitter("abcd"):
    el.extend(b);

unique =  sorted(set(el));

for prefix in unique:
    if prefix != "":
        print "value  " , prefix  , "- num of occurrences =   " , string.count(str(prefix));

I want to print all the permutation occurrence there is in string varaible.

since the permutation aren’t in the same length i want to fix the width and print it in a nice not like this one:

value   a - num of occurrences =    1
value   ab - num of occurrences =    1
value   abc - num of occurrences =    1
value   b - num of occurrences =    1
value   bc - num of occurrences =    1
value   bcd - num of occurrences =    1
value   c - num of occurrences =    1
value   cd - num of occurrences =    1
value   d - num of occurrences =    1

How can I use format to do it?

I found these posts but it didn’t go well with alphanumeric strings:

python string formatting fixed width

Setting fixed length with python


回答 0

编辑2013-12-11-这个答案很老了。它仍然是有效且正确的,但是关注此问题的人们应该更喜欢新格式的语法

您可以使用以下字符串格式

>>> print '%5s' % 'aa'
   aa
>>> print '%5s' % 'aaa'
  aaa
>>> print '%5s' % 'aaaa'
 aaaa
>>> print '%5s' % 'aaaaa'
aaaaa

基本上:

  • %字符运筹学Python它将不得不替代的东西令牌
  • s字符运筹学Python令牌将是一个字符串
  • 5(或任意你想要的号码)通知Python垫字符串用空格最多5个字符。

在您的特定情况下,可能的实现可能类似于:

>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
...     print 'value %3s - num of occurances = %d' % item # %d is the token of integers
... 
value   a - num of occurances = 1
value  ab - num of occurances = 1
value abc - num of occurances = 1

旁注:只是想知道您是否知道itertools模块的存在。例如,您可以使用以下命令在一行中获取所有组合的列表:

>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

,您可以combinations结合使用来获得出现次数count()

EDIT 2013-12-11 – This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax.

You can use string formatting like this:

>>> print '%5s' % 'aa'
   aa
>>> print '%5s' % 'aaa'
  aaa
>>> print '%5s' % 'aaaa'
 aaaa
>>> print '%5s' % 'aaaaa'
aaaaa

Basically:

  • the % character informs python it will have to substitute something to a token
  • the s character informs python the token will be a string
  • the 5 (or whatever number you wish) informs python to pad the string with spaces up to 5 characters.

In your specific case a possible implementation could look like:

>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
...     print 'value %3s - num of occurances = %d' % item # %d is the token of integers
... 
value   a - num of occurances = 1
value  ab - num of occurances = 1
value abc - num of occurances = 1

SIDE NOTE: Just wondered if you are aware of the existence of the itertools module. For example you could obtain a list of all your combinations in one line with:

>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

and you could get the number of occurrences by using combinations in conjunction with count().


回答 1

我发现使用str.format起来更加优雅:

>>> '{0: <5}'.format('ss')
'ss   '
>>> '{0: <5}'.format('sss')
'sss  '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'

如果要使字符串正确对齐,请使用>代替<

>>> '{0: >5}'.format('ss')
'   ss'

编辑:如注释中所述:0表示传递给的参数的索引str.format()

I find using str.format much more elegant:

>>> '{0: <5}'.format('s')
's    '
>>> '{0: <5}'.format('ss')
'ss   '
>>> '{0: <5}'.format('sss')
'sss  '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'

If you want to align the string to the right use > instead of <:

>>> '{0: >5}'.format('ss')
'   ss'

Edit 1: As mentioned in the comments: the 0 in '{0: <5}' indicates the argument’s index passed to str.format().


Edit 2: In python3 one could use also f-string:

sub_str='s'
for i in range(1,6):
    s = sub_str*i
    print(f'{s:>5}')
    
'    s'
'   ss'
'  sss'
' ssss'
'sssss'

or:

for i in range(1,5):
    s = sub_str*i
    print(f'{s:<5}')
's    '
'ss   '
'sss  '
'ssss '
'sssss'

of note, in some places above, ' ' (single quotation marks) were added to emphasize the width of the printed strings.


回答 2

最初是作为对@ 0x90答案的编辑而发布的,但是由于偏离了帖子的原始意图而被拒绝,建议将其发布为评论或答案,因此,我在此处包括简短的文章。

除了来自@ 0x90的答案,还可以通过使用宽度变量(根据@ user2763554的注释)来使语法更加灵活:

width=10
'{0: <{width}}'.format('sss', width=width)

此外,您可以仅通过使用数字并依靠传递给的参数的顺序来使表达式更简短format

width=10
'{0: <{1}}'.format('sss', width)

甚至不考虑所有数字,以获得最大的,可能是非Python隐式的紧凑性:

width=10
'{: <{}}'.format('sss', width)

更新2017-05-26

随着Python 3.6 中格式化字符串文字(简称为“ f-strings”)的引入,现在可以使用更简短的语法访问先前定义的变量:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

这也适用于字符串格式

>>> width=10
>>> string = 'sss'
>>> f'{string: <{width}}'
'sss       '

Originally posted as an edit to @0x90’s answer, but it got rejected for deviating from the post’s original intent and recommended to post as a comment or answer, so I’m including the short write-up here.

In addition to the answer from @0x90, the syntax can be made more flexible, by using a variable for the width (as per @user2763554’s comment):

width=10
'{0: <{width}}'.format('sss', width=width)

Further, you can make this expression briefer, by only using numbers and relying on the order of the arguments passed to format:

width=10
'{0: <{1}}'.format('sss', width)

Or even leave out all numbers for maximal, potentially non-pythonically implicit, compactness:

width=10
'{: <{}}'.format('sss', width)

Update 2017-05-26

With the introduction of formatted string literals (“f-strings” for short) in Python 3.6, it is now possible to access previously defined variables with a briefer syntax:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

This also applies to string formatting

>>> width=10
>>> string = 'sss'
>>> f'{string: <{width}}'
'sss       '

回答 3

format绝对是最优雅的方法,但是afaik不能在python的logging模块中使用它,因此这是使用%格式化的方法:

formatter = logging.Formatter(
    fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)

在此,-表示左对齐,而前面的数字s表示固定宽度。

一些示例输出:

2017-03-14 14:43:42,581 | this-app             | INFO       | running main
2017-03-14 14:43:42,581 | this-app.aux         | DEBUG      | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux         | INFO       | hello
2017-03-14 14:43:42,581 | this-app             | ERROR      | failed running main

此处的文档提供了更多信息:https : //docs.python.org/2/library/stdtypes.html#string-formatting-operations

format is definitely the most elegant way, but afaik you can’t use that with python’s logging module, so here’s how you can do it using the % formatting:

formatter = logging.Formatter(
    fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)

Here, the - indicates left-alignment, and the number before s indicates the fixed width.

Some sample output:

2017-03-14 14:43:42,581 | this-app             | INFO       | running main
2017-03-14 14:43:42,581 | this-app.aux         | DEBUG      | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux         | INFO       | hello
2017-03-14 14:43:42,581 | this-app             | ERROR      | failed running main

More info at the docs here: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations


回答 4

>>> print(f"{'123':<4}56789")
123 56789
>>> print(f"{'123':<4}56789")
123 56789

将timedelta格式化为字符串

问题:将timedelta格式化为字符串

我在格式化datetime.timedelta对象时遇到问题。

这是我要执行的操作:我有一个对象列表,并且该对象类的成员之一是timedelta对象,该对象显示事件的持续时间。我想以小时:分钟的格式显示该持续时间。

我尝试了多种方法来执行此操作,但遇到了困难。我当前的方法是为返回小时和分钟的对象添加方法。我可以将timedelta.seconds除以3600并四舍五入来获得小时数。我在获取剩余秒数并将其转换为分钟时遇到麻烦。

顺便说一句,我将Google AppEngine与Django模板结合使用进行演示。

I’m having trouble formatting a datetime.timedelta object.

Here’s what I’m trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.

I have tried a variety of methods for doing this and I’m having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I’m having trouble with getting the remainder seconds and converting that to minutes.

By the way, I’m using Google AppEngine with Django Templates for presentation.


回答 0

您可以使用str()将timedelta转换为字符串。这是一个例子:

import datetime
start = datetime.datetime(2009,2,10,14,00)
end   = datetime.datetime(2009,2,10,16,00)
delta = end-start
print(str(delta))
# prints 2:00:00

You can just convert the timedelta to a string with str(). Here’s an example:

import datetime
start = datetime.datetime(2009,2,10,14,00)
end   = datetime.datetime(2009,2,10,16,00)
delta = end-start
print(str(delta))
# prints 2:00:00

回答 1

如您所知,您可以通过访问.seconds属性从timedelta对象获取total_seconds 。

Python提供了内置函数divmod(),该函数允许:

s = 13420
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
print '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
# result: 03:43:40

或者您可以将模和减相结合,转换为小时和余数:

# arbitrary number of seconds
s = 13420
# hours
hours = s // 3600 
# remaining seconds
s = s - (hours * 3600)
# minutes
minutes = s // 60
# remaining seconds
seconds = s - (minutes * 60)
# total time
print '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
# result: 03:43:40

As you know, you can get the total_seconds from a timedelta object by accessing the .seconds attribute.

Python provides the builtin function divmod() which allows for:

s = 13420
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
print '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
# result: 03:43:40

or you can convert to hours and remainder by using a combination of modulo and subtraction:

# arbitrary number of seconds
s = 13420
# hours
hours = s // 3600 
# remaining seconds
s = s - (hours * 3600)
# minutes
minutes = s // 60
# remaining seconds
seconds = s - (minutes * 60)
# total time
print '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
# result: 03:43:40

回答 2

>>> str(datetime.timedelta(hours=10.56))
10:33:36

>>> td = datetime.timedelta(hours=10.505) # any timedelta object
>>> ':'.join(str(td).split(':')[:2])
10:30

如果我们简单地输入,将timedelta对象传递给str()函数将调用相同的格式代码print td。由于您不需要秒数,因此我们可以用冒号(3个部分)分割字符串,然后仅将前2个部分放回去。

>>> str(datetime.timedelta(hours=10.56))
10:33:36

>>> td = datetime.timedelta(hours=10.505) # any timedelta object
>>> ':'.join(str(td).split(':')[:2])
10:30

Passing the timedelta object to the str() function calls the same formatting code used if we simply type print td. Since you don’t want the seconds, we can split the string by colons (3 parts) and put it back together with only the first 2 parts.


回答 3

def td_format(td_object):
    seconds = int(td_object.total_seconds())
    periods = [
        ('year',        60*60*24*365),
        ('month',       60*60*24*30),
        ('day',         60*60*24),
        ('hour',        60*60),
        ('minute',      60),
        ('second',      1)
    ]

    strings=[]
    for period_name, period_seconds in periods:
        if seconds > period_seconds:
            period_value , seconds = divmod(seconds, period_seconds)
            has_s = 's' if period_value > 1 else ''
            strings.append("%s %s%s" % (period_value, period_name, has_s))

    return ", ".join(strings)
def td_format(td_object):
    seconds = int(td_object.total_seconds())
    periods = [
        ('year',        60*60*24*365),
        ('month',       60*60*24*30),
        ('day',         60*60*24),
        ('hour',        60*60),
        ('minute',      60),
        ('second',      1)
    ]

    strings=[]
    for period_name, period_seconds in periods:
        if seconds > period_seconds:
            period_value , seconds = divmod(seconds, period_seconds)
            has_s = 's' if period_value > 1 else ''
            strings.append("%s %s%s" % (period_value, period_name, has_s))

    return ", ".join(strings)

回答 4

我个人使用该humanize库:

>>> import datetime
>>> humanize.naturalday(datetime.datetime.now())
'today'
>>> humanize.naturalday(datetime.datetime.now() - datetime.timedelta(days=1))
'yesterday'
>>> humanize.naturalday(datetime.date(2007, 6, 5))
'Jun 05'
>>> humanize.naturaldate(datetime.date(2007, 6, 5))
'Jun 05 2007'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=1))
'a second ago'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600))
'an hour ago'

当然,它并不能完全给您为您的答案(的确是,str(timeA - timeB)但是我发现,一旦您超过几个小时,显示就会迅速变得不可读。humanize它支持更大的值易于阅读,并且位置很好。

contrib.humanize显然,它是受Django 模块启发的,因此,由于您使用的是Django,您应该使用它。

I personally use the humanize library for this:

>>> import datetime
>>> humanize.naturalday(datetime.datetime.now())
'today'
>>> humanize.naturalday(datetime.datetime.now() - datetime.timedelta(days=1))
'yesterday'
>>> humanize.naturalday(datetime.date(2007, 6, 5))
'Jun 05'
>>> humanize.naturaldate(datetime.date(2007, 6, 5))
'Jun 05 2007'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=1))
'a second ago'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600))
'an hour ago'

Of course, it doesn’t give you exactly the answer you were looking for (which is, indeed, str(timeA - timeB), but I have found that once you go beyond a few hours, the display becomes quickly unreadable. humanize has support for much larger values that are human-readable, and is also well localized.

It’s inspired by Django’s contrib.humanize module, apparently, so since you are using Django, you should probably use that.


回答 5

他已经有一个timedelta对象,所以为什么不使用其内置方法total_seconds()将其转换为秒,然后使用divmod()获得小时和分钟呢?

hours, remainder = divmod(myTimeDelta.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)

# Formatted only for hours and minutes as requested
print '%s:%s' % (hours, minutes)

无论时间增量是偶数天还是数年,这都有效。

He already has a timedelta object so why not use its built-in method total_seconds() to convert it to seconds, then use divmod() to get hours and minutes?

hours, remainder = divmod(myTimeDelta.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)

# Formatted only for hours and minutes as requested
print '%s:%s' % (hours, minutes)

This works regardless if the time delta has even days or years.


回答 6

这是一个通用函数,用于将timedelta对象或常规数字(以秒或分钟等形式)转换为格式正确的字符串。我对一个重复的问题做了mpounsett的出色回答,使其更加灵活,可读性更高,并增加了文档。

您会发现,到目前为止,这是最灵活的答案,因为它可以使您:

  1. 即时自定义字符串格式,而不是对其进行硬编码。
  2. 留出一定的时间间隔没有问题(请参见下面的示例)。

功能:

from string import Formatter
from datetime import timedelta

def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', inputtype='timedelta'):
    """Convert a datetime.timedelta object or a regular number to a custom-
    formatted string, just like the stftime() method does for datetime.datetime
    objects.

    The fmt argument allows custom formatting to be specified.  Fields can 
    include seconds, minutes, hours, days, and weeks.  Each field is optional.

    Some examples:
        '{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)
        '{W}w {D}d {H}:{M:02}:{S:02}'     --> '4w 5d 8:04:02'
        '{D:2}d {H:2}:{M:02}:{S:02}'      --> ' 5d  8:04:02'
        '{H}h {S}s'                       --> '72h 800s'

    The inputtype argument allows tdelta to be a regular number instead of the  
    default, which is a datetime.timedelta object.  Valid inputtype strings: 
        's', 'seconds', 
        'm', 'minutes', 
        'h', 'hours', 
        'd', 'days', 
        'w', 'weeks'
    """

    # Convert tdelta to integer seconds.
    if inputtype == 'timedelta':
        remainder = int(tdelta.total_seconds())
    elif inputtype in ['s', 'seconds']:
        remainder = int(tdelta)
    elif inputtype in ['m', 'minutes']:
        remainder = int(tdelta)*60
    elif inputtype in ['h', 'hours']:
        remainder = int(tdelta)*3600
    elif inputtype in ['d', 'days']:
        remainder = int(tdelta)*86400
    elif inputtype in ['w', 'weeks']:
        remainder = int(tdelta)*604800

    f = Formatter()
    desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]
    possible_fields = ('W', 'D', 'H', 'M', 'S')
    constants = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
    values = {}
    for field in possible_fields:
        if field in desired_fields and field in constants:
            values[field], remainder = divmod(remainder, constants[field])
    return f.format(fmt, **values)

演示:

>>> td = timedelta(days=2, hours=3, minutes=5, seconds=8, microseconds=340)

>>> print strfdelta(td)
02d 03h 05m 08s

>>> print strfdelta(td, '{D}d {H}:{M:02}:{S:02}')
2d 3:05:08

>>> print strfdelta(td, '{D:2}d {H:2}:{M:02}:{S:02}')
 2d  3:05:08

>>> print strfdelta(td, '{H}h {S}s')
51h 308s

>>> print strfdelta(12304, inputtype='s')
00d 03h 25m 04s

>>> print strfdelta(620, '{H}:{M:02}', 'm')
10:20

>>> print strfdelta(49, '{D}d {H}h', 'h')
2d 1h

Here is a general purpose function for converting either a timedelta object or a regular number (in the form of seconds or minutes, etc.) to a nicely formatted string. I took mpounsett’s fantastic answer on a duplicate question, made it a bit more flexible, improved readibility, and added documentation.

You will find that it is the most flexible answer here so far since it allows you to:

  1. Customize the string format on the fly instead of it being hard-coded.
  2. Leave out certain time intervals without a problem (see examples below).

Function:

from string import Formatter
from datetime import timedelta

def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', inputtype='timedelta'):
    """Convert a datetime.timedelta object or a regular number to a custom-
    formatted string, just like the stftime() method does for datetime.datetime
    objects.

    The fmt argument allows custom formatting to be specified.  Fields can 
    include seconds, minutes, hours, days, and weeks.  Each field is optional.

    Some examples:
        '{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)
        '{W}w {D}d {H}:{M:02}:{S:02}'     --> '4w 5d 8:04:02'
        '{D:2}d {H:2}:{M:02}:{S:02}'      --> ' 5d  8:04:02'
        '{H}h {S}s'                       --> '72h 800s'

    The inputtype argument allows tdelta to be a regular number instead of the  
    default, which is a datetime.timedelta object.  Valid inputtype strings: 
        's', 'seconds', 
        'm', 'minutes', 
        'h', 'hours', 
        'd', 'days', 
        'w', 'weeks'
    """

    # Convert tdelta to integer seconds.
    if inputtype == 'timedelta':
        remainder = int(tdelta.total_seconds())
    elif inputtype in ['s', 'seconds']:
        remainder = int(tdelta)
    elif inputtype in ['m', 'minutes']:
        remainder = int(tdelta)*60
    elif inputtype in ['h', 'hours']:
        remainder = int(tdelta)*3600
    elif inputtype in ['d', 'days']:
        remainder = int(tdelta)*86400
    elif inputtype in ['w', 'weeks']:
        remainder = int(tdelta)*604800

    f = Formatter()
    desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]
    possible_fields = ('W', 'D', 'H', 'M', 'S')
    constants = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
    values = {}
    for field in possible_fields:
        if field in desired_fields and field in constants:
            values[field], remainder = divmod(remainder, constants[field])
    return f.format(fmt, **values)

Demo:

>>> td = timedelta(days=2, hours=3, minutes=5, seconds=8, microseconds=340)

>>> print strfdelta(td)
02d 03h 05m 08s

>>> print strfdelta(td, '{D}d {H}:{M:02}:{S:02}')
2d 3:05:08

>>> print strfdelta(td, '{D:2}d {H:2}:{M:02}:{S:02}')
 2d  3:05:08

>>> print strfdelta(td, '{H}h {S}s')
51h 308s

>>> print strfdelta(12304, inputtype='s')
00d 03h 25m 04s

>>> print strfdelta(620, '{H}:{M:02}', 'm')
10:20

>>> print strfdelta(49, '{D}d {H}h', 'h')
2d 1h

回答 7

我知道这是一个古老的已回答问题,但我datetime.utcfromtimestamp()为此使用了。它需要秒数并返回datetime可以像其他格式一样设置的datetime

duration = datetime.utcfromtimestamp(end - begin)
print duration.strftime('%H:%M')

只要您停留在合法的时间范围内,它就应该起作用,即,当小时数小于等于23时,它不会返回1234:35。

I know that this is an old answered question, but I use datetime.utcfromtimestamp() for this. It takes the number of seconds and returns a datetime that can be formatted like any other datetime.

duration = datetime.utcfromtimestamp(end - begin)
print duration.strftime('%H:%M')

As long as you stay in the legal ranges for the time parts this should work, i.e. it doesn’t return 1234:35 as hours are <= 23.


回答 8

发问者想要比典型的更好的格式:

  >>> import datetime
  >>> datetime.timedelta(seconds=41000)
  datetime.timedelta(0, 41000)
  >>> str(datetime.timedelta(seconds=41000))
  '11:23:20'
  >>> str(datetime.timedelta(seconds=4102.33))
  '1:08:22.330000'
  >>> str(datetime.timedelta(seconds=413302.33))
  '4 days, 18:48:22.330000'

因此,实际上有两种格式,一种格式的天数为0,而被忽略,另一种格式的文本为“ n days,h:m:s”。但是,秒可能会有分数,并且打印输出中没有前导零,所以列很乱。

如果您喜欢,这是我的日常工作:

def printNiceTimeDelta(stime, etime):
    delay = datetime.timedelta(seconds=(etime - stime))
    if (delay.days > 0):
        out = str(delay).replace(" days, ", ":")
    else:
        out = "0:" + str(delay)
    outAr = out.split(':')
    outAr = ["%02d" % (int(float(x))) for x in outAr]
    out   = ":".join(outAr)
    return out

这将以dd:hh:mm:ss格式返回输出:

00:00:00:15
00:00:00:19
02:01:31:40
02:01:32:22

我确实考虑过要增加几年,但这留给读者练习,因为输出在1年以上是安全的:

>>> str(datetime.timedelta(seconds=99999999))
'1157 days, 9:46:39'

Questioner wants a nicer format than the typical:

  >>> import datetime
  >>> datetime.timedelta(seconds=41000)
  datetime.timedelta(0, 41000)
  >>> str(datetime.timedelta(seconds=41000))
  '11:23:20'
  >>> str(datetime.timedelta(seconds=4102.33))
  '1:08:22.330000'
  >>> str(datetime.timedelta(seconds=413302.33))
  '4 days, 18:48:22.330000'

So, really there’s two formats, one where days are 0 and it’s left out, and another where there’s text “n days, h:m:s”. But, the seconds may have fractions, and there’s no leading zeroes in the printouts, so columns are messy.

Here’s my routine, if you like it:

def printNiceTimeDelta(stime, etime):
    delay = datetime.timedelta(seconds=(etime - stime))
    if (delay.days > 0):
        out = str(delay).replace(" days, ", ":")
    else:
        out = "0:" + str(delay)
    outAr = out.split(':')
    outAr = ["%02d" % (int(float(x))) for x in outAr]
    out   = ":".join(outAr)
    return out

this returns output as dd:hh:mm:ss format:

00:00:00:15
00:00:00:19
02:01:31:40
02:01:32:22

I did think about adding years to this, but this is left as an exercise for the reader, since the output is safe at over 1 year:

>>> str(datetime.timedelta(seconds=99999999))
'1157 days, 9:46:39'

回答 9

我会在这里认真考虑Occam的Razor方法:

td = str(timedelta).split('.')[0]

这将返回不带微秒的字符串

如果要重新生成datetime.timedelta对象,请执行以下操作:

h,m,s = re.split(':', td)
new_delta = datetime.timedelta(hours=int(h),minutes=int(m),seconds=int(s))

2年过去了,我喜欢这种语言!

I would seriously consider the Occam’s Razor approach here:

td = str(timedelta).split('.')[0]

This returns a string without the microseconds

If you want to regenerate the datetime.timedelta object, just do this:

h,m,s = re.split(':', td)
new_delta = datetime.timedelta(hours=int(h),minutes=int(m),seconds=int(s))

2 years in, I love this language!


回答 10

我的datetime.timedelta物品超过一天。因此,这是另一个问题。以上所有讨论都假设不到一天。A timedelta实际上是天,秒和微秒的元组。上面的讨论应该使用td.seconds像joe一样,但是如果您有工作日,则它不包括在seconds值中。

我得到了2个日期时间与打印天数和小时之间的时间跨度。

span = currentdt - previousdt
print '%d,%d\n' % (span.days,span.seconds/3600)

My datetime.timedelta objects went greater than a day. So here is a further problem. All the discussion above assumes less than a day. A timedelta is actually a tuple of days, seconds and microseconds. The above discussion should use td.seconds as joe did, but if you have days it is NOT included in the seconds value.

I am getting a span of time between 2 datetimes and printing days and hours.

span = currentdt - previousdt
print '%d,%d\n' % (span.days,span.seconds/3600)

回答 11

我使用humanfriendlypython库来做到这一点,它工作得很好。

import humanfriendly
from datetime import timedelta
delta = timedelta(seconds = 321)
humanfriendly.format_timespan(delta)

'5 minutes and 21 seconds'

可在https://pypi.org/project/humanfriendly/

I used the humanfriendly python library to do this, it works very well.

import humanfriendly
from datetime import timedelta
delta = timedelta(seconds = 321)
humanfriendly.format_timespan(delta)

'5 minutes and 21 seconds'

Available at https://pypi.org/project/humanfriendly/


回答 12

遵循上面Joe的示例值,因此,我将使用模数算术运算符:

td = datetime.timedelta(hours=10.56)
td_str = "%d:%d" % (td.seconds/3600, td.seconds%3600/60)

注意,Python中的整数除法默认舍入;如果要更明确,请适当使用math.floor()或math.ceil()。

Following Joe’s example value above, I’d use the modulus arithmetic operator, thusly:

td = datetime.timedelta(hours=10.56)
td_str = "%d:%d" % (td.seconds/3600, td.seconds%3600/60)

Note that integer division in Python rounds down by default; if you want to be more explicit, use math.floor() or math.ceil() as appropriate.


回答 13

def seconds_to_time_left_string(total_seconds):
    s = int(total_seconds)
    years = s // 31104000
    if years > 1:
        return '%d years' % years
    s = s - (years * 31104000)
    months = s // 2592000
    if years == 1:
        r = 'one year'
        if months > 0:
            r += ' and %d months' % months
        return r
    if months > 1:
        return '%d months' % months
    s = s - (months * 2592000)
    days = s // 86400
    if months == 1:
        r = 'one month'
        if days > 0:
            r += ' and %d days' % days
        return r
    if days > 1:
        return '%d days' % days
    s = s - (days * 86400)
    hours = s // 3600
    if days == 1:
        r = 'one day'
        if hours > 0:
            r += ' and %d hours' % hours
        return r 
    s = s - (hours * 3600)
    minutes = s // 60
    seconds = s - (minutes * 60)
    if hours >= 6:
        return '%d hours' % hours
    if hours >= 1:
        r = '%d hours' % hours
        if hours == 1:
            r = 'one hour'
        if minutes > 0:
            r += ' and %d minutes' % minutes
        return r
    if minutes == 1:
        r = 'one minute'
        if seconds > 0:
            r += ' and %d seconds' % seconds
        return r
    if minutes == 0:
        return '%d seconds' % seconds
    if seconds == 0:
        return '%d minutes' % minutes
    return '%d minutes and %d seconds' % (minutes, seconds)

for i in range(10):
    print pow(8, i), seconds_to_time_left_string(pow(8, i))


Output:
1 1 seconds
8 8 seconds
64 one minute and 4 seconds
512 8 minutes and 32 seconds
4096 one hour and 8 minutes
32768 9 hours
262144 3 days
2097152 24 days
16777216 6 months
134217728 4 years
def seconds_to_time_left_string(total_seconds):
    s = int(total_seconds)
    years = s // 31104000
    if years > 1:
        return '%d years' % years
    s = s - (years * 31104000)
    months = s // 2592000
    if years == 1:
        r = 'one year'
        if months > 0:
            r += ' and %d months' % months
        return r
    if months > 1:
        return '%d months' % months
    s = s - (months * 2592000)
    days = s // 86400
    if months == 1:
        r = 'one month'
        if days > 0:
            r += ' and %d days' % days
        return r
    if days > 1:
        return '%d days' % days
    s = s - (days * 86400)
    hours = s // 3600
    if days == 1:
        r = 'one day'
        if hours > 0:
            r += ' and %d hours' % hours
        return r 
    s = s - (hours * 3600)
    minutes = s // 60
    seconds = s - (minutes * 60)
    if hours >= 6:
        return '%d hours' % hours
    if hours >= 1:
        r = '%d hours' % hours
        if hours == 1:
            r = 'one hour'
        if minutes > 0:
            r += ' and %d minutes' % minutes
        return r
    if minutes == 1:
        r = 'one minute'
        if seconds > 0:
            r += ' and %d seconds' % seconds
        return r
    if minutes == 0:
        return '%d seconds' % seconds
    if seconds == 0:
        return '%d minutes' % minutes
    return '%d minutes and %d seconds' % (minutes, seconds)

for i in range(10):
    print pow(8, i), seconds_to_time_left_string(pow(8, i))


Output:
1 1 seconds
8 8 seconds
64 one minute and 4 seconds
512 8 minutes and 32 seconds
4096 one hour and 8 minutes
32768 9 hours
262144 3 days
2097152 24 days
16777216 6 months
134217728 4 years

回答 14

我在工作中加班计算的输出也有类似的问题。该值应始终以HH:MM显示,即使该值大于一天并且该值可能会变为负数。我合并了一些所示的解决方案,也许其他人认为此解决方案很有用。我意识到,如果timedelta值为负,则大多数使用divmod方法显示的解决方案都无法立即使用:

def td2HHMMstr(td):
  '''Convert timedelta objects to a HH:MM string with (+/-) sign'''
  if td < datetime.timedelta(seconds=0):
    sign='-'
    td = -td
  else:
    sign = ''
  tdhours, rem = divmod(td.total_seconds(), 3600)
  tdminutes, rem = divmod(rem, 60)
  tdstr = '{}{:}:{:02d}'.format(sign, int(tdhours), int(tdminutes))
  return tdstr

timedelta到HH:MM字符串:

td2HHMMstr(datetime.timedelta(hours=1, minutes=45))
'1:54'

td2HHMMstr(datetime.timedelta(days=2, hours=3, minutes=2))
'51:02'

td2HHMMstr(datetime.timedelta(hours=-3, minutes=-2))
'-3:02'

td2HHMMstr(datetime.timedelta(days=-35, hours=-3, minutes=-2))
'-843:02'

I had a similar problem with the output of overtime calculation at work. The value should always show up in HH:MM, even when it is greater than one day and the value can get negative. I combined some of the shown solutions and maybe someone else find this solution useful. I realized that if the timedelta value is negative most of the shown solutions with the divmod method doesn’t work out of the box:

def td2HHMMstr(td):
  '''Convert timedelta objects to a HH:MM string with (+/-) sign'''
  if td < datetime.timedelta(seconds=0):
    sign='-'
    td = -td
  else:
    sign = ''
  tdhours, rem = divmod(td.total_seconds(), 3600)
  tdminutes, rem = divmod(rem, 60)
  tdstr = '{}{:}:{:02d}'.format(sign, int(tdhours), int(tdminutes))
  return tdstr

timedelta to HH:MM string:

td2HHMMstr(datetime.timedelta(hours=1, minutes=45))
'1:54'

td2HHMMstr(datetime.timedelta(days=2, hours=3, minutes=2))
'51:02'

td2HHMMstr(datetime.timedelta(hours=-3, minutes=-2))
'-3:02'

td2HHMMstr(datetime.timedelta(days=-35, hours=-3, minutes=-2))
'-843:02'

回答 15

import datetime
hours = datetime.timedelta(hours=16, minutes=30)
print((datetime.datetime(1,1,1) + hours).strftime('%H:%M'))
import datetime
hours = datetime.timedelta(hours=16, minutes=30)
print((datetime.datetime(1,1,1) + hours).strftime('%H:%M'))

回答 16

直接解决此问题的模板过滤器。内置函数int()从不舍入。F字符串(即f”)需要python 3.6。

@app_template_filter()
def diffTime(end, start):
    diff = (end - start).total_seconds()
    d = int(diff / 86400)
    h = int((diff - (d * 86400)) / 3600)
    m = int((diff - (d * 86400 + h * 3600)) / 60)
    s = int((diff - (d * 86400 + h * 3600 + m *60)))
    if d > 0:
        fdiff = f'{d}d {h}h {m}m {s}s'
    elif h > 0:
        fdiff = f'{h}h {m}m {s}s'
    elif m > 0:
        fdiff = f'{m}m {s}s'
    else:
        fdiff = f'{s}s'
    return fdiff

A straight forward template filter for this problem. The built-in function int() never rounds up. F-Strings (i.e. f”) require python 3.6.

@app_template_filter()
def diffTime(end, start):
    diff = (end - start).total_seconds()
    d = int(diff / 86400)
    h = int((diff - (d * 86400)) / 3600)
    m = int((diff - (d * 86400 + h * 3600)) / 60)
    s = int((diff - (d * 86400 + h * 3600 + m *60)))
    if d > 0:
        fdiff = f'{d}d {h}h {m}m {s}s'
    elif h > 0:
        fdiff = f'{h}h {m}m {s}s'
    elif m > 0:
        fdiff = f'{m}m {s}s'
    else:
        fdiff = f'{s}s'
    return fdiff

回答 17

from django.utils.translation import ngettext

def localize_timedelta(delta):
    ret = []
    num_years = int(delta.days / 365)
    if num_years > 0:
        delta -= timedelta(days=num_years * 365)
        ret.append(ngettext('%d year', '%d years', num_years) % num_years)

    if delta.days > 0:
        ret.append(ngettext('%d day', '%d days', delta.days) % delta.days)

    num_hours = int(delta.seconds / 3600)
    if num_hours > 0:
        delta -= timedelta(hours=num_hours)
        ret.append(ngettext('%d hour', '%d hours', num_hours) % num_hours)

    num_minutes = int(delta.seconds / 60)
    if num_minutes > 0:
        ret.append(ngettext('%d minute', '%d minutes', num_minutes) % num_minutes)

    return ' '.join(ret)

这将生成:

>>> from datetime import timedelta
>>> localize_timedelta(timedelta(days=3660, minutes=500))
'10 years 10 days 8 hours 20 minutes'
from django.utils.translation import ngettext

def localize_timedelta(delta):
    ret = []
    num_years = int(delta.days / 365)
    if num_years > 0:
        delta -= timedelta(days=num_years * 365)
        ret.append(ngettext('%d year', '%d years', num_years) % num_years)

    if delta.days > 0:
        ret.append(ngettext('%d day', '%d days', delta.days) % delta.days)

    num_hours = int(delta.seconds / 3600)
    if num_hours > 0:
        delta -= timedelta(hours=num_hours)
        ret.append(ngettext('%d hour', '%d hours', num_hours) % num_hours)

    num_minutes = int(delta.seconds / 60)
    if num_minutes > 0:
        ret.append(ngettext('%d minute', '%d minutes', num_minutes) % num_minutes)

    return ' '.join(ret)

This will produce:

>>> from datetime import timedelta
>>> localize_timedelta(timedelta(days=3660, minutes=500))
'10 years 10 days 8 hours 20 minutes'

回答 18

请检查此功能-它会将timedelta对象转换为字符串’HH:MM:SS’

def format_timedelta(td):
    hours, remainder = divmod(td.total_seconds(), 3600)
    minutes, seconds = divmod(remainder, 60)
    hours, minutes, seconds = int(hours), int(minutes), int(seconds)
    if hours < 10:
        hours = '0%s' % int(hours)
    if minutes < 10:
        minutes = '0%s' % minutes
    if seconds < 10:
        seconds = '0%s' % seconds
    return '%s:%s:%s' % (hours, minutes, seconds)

Please check this function – it converts timedelta object into string ‘HH:MM:SS’

def format_timedelta(td):
    hours, remainder = divmod(td.total_seconds(), 3600)
    minutes, seconds = divmod(remainder, 60)
    hours, minutes, seconds = int(hours), int(minutes), int(seconds)
    if hours < 10:
        hours = '0%s' % int(hours)
    if minutes < 10:
        minutes = '0%s' % minutes
    if seconds < 10:
        seconds = '0%s' % seconds
    return '%s:%s:%s' % (hours, minutes, seconds)

回答 19

一支班轮。由于timedelta不提供datetime的strftime,因此请将timedelta带回datetime,然后使用stftime。

这不仅可以实现OP要求的格式Hours:Minutes,现在,如果您的需求更改为其他表示形式,则可以利用datetime的strftime的完整格式化功能。

import datetime
td = datetime.timedelta(hours=2, minutes=10, seconds=5)
print(td)
print(datetime.datetime.strftime(datetime.datetime.strptime(str(td), "%H:%M:%S"), "%H:%M"))

Output:
2:10:05
02:10

这也解决了将时间增量格式化为H:MM:SS而不是HH:MM:SS的麻烦,这导致了我遇到这个问题,并且分享了我的解决方案。

One liner. Since timedeltas do not offer datetime’s strftime, bring the timedelta back to a datetime, and use stftime.

This can not only achieve the OP’s requested format Hours:Minutes, now you can leverage the full formatting power of datetime’s strftime, should your requirements change to another representation.

import datetime
td = datetime.timedelta(hours=2, minutes=10, seconds=5)
print(td)
print(datetime.datetime.strftime(datetime.datetime.strptime(str(td), "%H:%M:%S"), "%H:%M"))

Output:
2:10:05
02:10

This also solves the annoyance that timedeltas are formatted into strings as H:MM:SS rather than HH:MM:SS, which lead me to this problem, and the solution I’ve shared.


回答 20

如果您已经有一个timedelta obj,则只需将该obj转换为字符串即可。删除字符串的最后3个字符并打印。这将截断秒数部分,并以小时:分钟的格式打印其余部分。

t = str(timedeltaobj) 

print t[:-3]

If you already have a timedelta obj then just convert that obj into string. Remove the last 3 characters of the string and print. This will truncate the seconds part and print the rest of it in the format Hours:Minutes.

t = str(timedeltaobj) 

print t[:-3]

回答 21

如果您恰好IPython在包装中(应该如此),则它具有(到目前为止,无论如何)持续时间非常长的格式化程序(以秒为单位)。那是在各个地方使用的,例如%%time细胞魔术。我喜欢它能短期产生的格式:

>>> from IPython.core.magics.execution import _format_time
>>> 
>>> for v in range(-9, 10, 2):
...     dt = 1.25 * 10**v
...     print(_format_time(dt))

1.25 ns
125 ns
12.5 µs
1.25 ms
125 ms
12.5 s
20min 50s
1d 10h 43min 20s
144d 16h 13min 20s
14467d 14h 13min 20s

If you happen to have IPython in your packages (you should), it has (up to now, anyway) a very nice formatter for durations (in float seconds). That is used in various places, for example by the %%time cell magic. I like the format it produces for short durations:

>>> from IPython.core.magics.execution import _format_time
>>> 
>>> for v in range(-9, 10, 2):
...     dt = 1.25 * 10**v
...     print(_format_time(dt))

1.25 ns
125 ns
12.5 µs
1.25 ms
125 ms
12.5 s
20min 50s
1d 10h 43min 20s
144d 16h 13min 20s
14467d 14h 13min 20s

回答 22

t1 = datetime.datetime.strptime(StartTime, "%H:%M:%S %d-%m-%y")

t2 = datetime.datetime.strptime(EndTime, "%H:%M:%S %d-%m-%y")

return str(t2-t1)

因此对于:

StartTime = '15:28:53 21-07-13'
EndTime = '15:32:40 21-07-13'

返回:

'0:03:47'
t1 = datetime.datetime.strptime(StartTime, "%H:%M:%S %d-%m-%y")

t2 = datetime.datetime.strptime(EndTime, "%H:%M:%S %d-%m-%y")

return str(t2-t1)

So for:

StartTime = '15:28:53 21-07-13'
EndTime = '15:32:40 21-07-13'

returns:

'0:03:47'

回答 23

感谢大家的帮助。我采纳了您的许多想法并将它们组合在一起,让我知道您的想法。

我向此类添加了两个方法:

def hours(self):
    retval = ""
    if self.totalTime:
        hoursfloat = self.totalTime.seconds / 3600
        retval = round(hoursfloat)
    return retval

def minutes(self):
    retval = ""
    if self.totalTime:
        minutesfloat = self.totalTime.seconds / 60
        hoursAsMinutes = self.hours() * 60
        retval = round(minutesfloat - hoursAsMinutes)
    return retval

在我的django中,我使用了这个(sum是对象,它在字典中):

<td>{{ sum.0 }}</td>    
<td>{{ sum.1.hours|stringformat:"d" }}:{{ sum.1.minutes|stringformat:"#02.0d" }}</td>

Thanks everyone for your help. I took many of your ideas and put them together, let me know what you think.

I added two methods to the class like this:

def hours(self):
    retval = ""
    if self.totalTime:
        hoursfloat = self.totalTime.seconds / 3600
        retval = round(hoursfloat)
    return retval

def minutes(self):
    retval = ""
    if self.totalTime:
        minutesfloat = self.totalTime.seconds / 60
        hoursAsMinutes = self.hours() * 60
        retval = round(minutesfloat - hoursAsMinutes)
    return retval

In my django I used this (sum is the object and it is in a dictionary):

<td>{{ sum.0 }}</td>    
<td>{{ sum.1.hours|stringformat:"d" }}:{{ sum.1.minutes|stringformat:"#02.0d" }}</td>

如何在python字符串中打印文字大括号字符并在其上使用.format?

问题:如何在python字符串中打印文字大括号字符并在其上使用.format?

x = " \{ Hello \} {0} "
print(x.format(42))

给我 : Key Error: Hello\\

我想打印输出: {Hello} 42

x = " \{ Hello \} {0} "
print(x.format(42))

gives me : Key Error: Hello\\

I want to print the output: {Hello} 42


回答 0

您需要将{{和加倍}}

>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '

这是Python文档中有关格式字符串语法的相关部分:

格式字符串包含用花括号括起来的“替换字段” {}。花括号中不包含的所有内容均视为文字文本,该文本原样复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍:{{和来对其进行转义}}

You need to double the {{ and }}:

>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '

Here’s the relevant part of the Python documentation for format string syntax:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.


回答 1

您可以通过将花括号加倍来逃脱它。

例如:

x = "{{ Hello }} {0}"
print(x.format(42))

You escape it by doubling the braces.

Eg:

x = "{{ Hello }} {0}"
print(x.format(42))

回答 2

Python 3.6+(2017年)

在最新版本的Python中,将使用f字符串(另请参阅PEP498)。

对于f弦,应使用double {{}}

n = 42  
print(f" {{Hello}} {n} ")

产生所需的

 {Hello} 42

如果您需要在方括号中解析表达式而不是使用文字文本,则需要三组方括号:

hello = "HELLO"
print(f"{{{hello.lower()}}}")

产生

{hello}

Python 3.6+ (2017)

In the recent versions of Python one would use f-strings (see also PEP498).

With f-strings one should use double {{ or }}

n = 42  
print(f" {{Hello}} {n} ")

produces the desired

 {Hello} 42

If you need to resolve an expression in the brackets instead of using literal text you’ll need three sets of brackets:

hello = "HELLO"
print(f"{{{hello.lower()}}}")

produces

{hello}

回答 3

OP写了这个评论:

我正在尝试出于某种目的格式化小型JSON,例如:'{"all": false, "selected": "{}"}'.format(data)获得类似{"all": false, "selected": "1,2"}

在处理JSON时经常会出现“转义括号”问题。

我建议这样做:

import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)

它比替代方案更清洁,替代方案是:

'{{"all": false, "selected": "{}"}}'.format(data)

json当JSON字符串比示例复杂时,最好使用该库。

The OP wrote this comment:

I was trying to format a small JSON for some purposes, like this: '{"all": false, "selected": "{}"}'.format(data) to get something like {"all": false, "selected": "1,2"}

It’s pretty common that the “escaping braces” issue comes up when dealing with JSON.

I suggest doing this:

import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)

It’s cleaner than the alternative, which is:

'{{"all": false, "selected": "{}"}}'.format(data)

Using the json library is definitely preferable when the JSON string gets more complicated than the example.


回答 4

尝试这样做:

x = " {{ Hello }} {0} "
print x.format(42)

Try doing this:

x = " {{ Hello }} {0} "
print x.format(42)

回答 5

尝试这个:

x = "{{ Hello }} {0}"

Try this:

x = "{{ Hello }} {0}"


回答 6

尽管没有更好的效果,但仅供参考,您也可以这样做:

>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42

例如,当有人要打印时,此功能很有用{argument}。它可能比'{{{}}}'.format('argument')

请注意,您在Python 2.7之后省略了参数位置(例如{}而不是{0}

Although not any better, just for the reference, you can also do this:

>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42

It can be useful for example when someone wants to print {argument}. It is maybe more readable than '{{{}}}'.format('argument')

Note that you omit argument positions (e.g. {} instead of {0}) after Python 2.7


回答 7

如果您打算做很多事情,最好定义一个实用函数,让您使用任意大括号替代项,例如

def custom_format(string, brackets, *args, **kwargs):
    if len(brackets) != 2:
        raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
    padded = string.replace('{', '{{').replace('}', '}}')
    substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
    formatted = substituted.format(*args, **kwargs)
    return formatted

>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'

请注意,这将适用于括号为长度为2的字符串或两个字符串为可迭代的字符串(对于多字符定界符)。

If you are going to be doing this a lot, it might be good to define a utility function that will let you use arbitrary brace substitutes instead, like

def custom_format(string, brackets, *args, **kwargs):
    if len(brackets) != 2:
        raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
    padded = string.replace('{', '{{').replace('}', '}}')
    substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
    formatted = substituted.format(*args, **kwargs)
    return formatted

>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'

Note that this will work either with brackets being a string of length 2 or an iterable of two strings (for multi-character delimiters).


回答 8

我最近遇到了这个问题,因为我想将字符串注入预先格式化的JSON中。我的解决方案是创建一个辅助方法,如下所示:

def preformat(msg):
    """ allow {{key}} to be used for formatting in text
    that already uses curly braces.  First switch this into
    something else, replace curlies with double curlies, and then
    switch back to regular braces
    """
    msg = msg.replace('{{', '<<<').replace('}}', '>>>')
    msg = msg.replace('{', '{{').replace('}', '}}')
    msg = msg.replace('<<<', '{').replace('>>>', '}')
    return msg

然后,您可以执行以下操作:

formatted = preformat("""
    {
        "foo": "{{bar}}"
    }""").format(bar="gas")

如果性能不成问题,则完成工作。

I recently ran into this, because I wanted to inject strings into preformatted JSON. My solution was to create a helper method, like this:

def preformat(msg):
    """ allow {{key}} to be used for formatting in text
    that already uses curly braces.  First switch this into
    something else, replace curlies with double curlies, and then
    switch back to regular braces
    """
    msg = msg.replace('{{', '<<<').replace('}}', '>>>')
    msg = msg.replace('{', '{{').replace('}', '}}')
    msg = msg.replace('<<<', '{').replace('>>>', '}')
    return msg

You can then do something like:

formatted = preformat("""
    {
        "foo": "{{bar}}"
    }""").format(bar="gas")

Gets the job done if performance is not an issue.


回答 9

如果需要在字符串中保留两个大括号,则变量的每一侧都需要5个大括号。

>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'

If you need to keep two curly braces in the string, you need 5 curly braces on each side of the variable.

>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'

回答 10

原因是,{}.format()您的情况下的语法,因此.format()无法识别,{Hello}因此引发了错误。

您可以使用双大括号{{}}覆盖它,

x = " {{ Hello }} {0} "

要么

尝试%s格式化文本,

x = " { Hello } %s"
print x%(42)  

Reason is , {} is the syntax of .format() so in your case .format() doesn’t recognize {Hello} so it threw an error.

you can override it by using double curly braces {{}},

x = " {{ Hello }} {0} "

or

try %s for text formatting,

x = " { Hello } %s"
print x%(42)  

回答 11

我在尝试打印文本时偶然发现了这个问题,可以将其复制粘贴到Latex文档中。我扩展这个答案,并使用命名的替换字段:

假设您要打印出带有诸如的索引的多个变量的乘积 ,在Latex中将是$A_{ 0042 }*A_{ 3141 }*A_{ 2718 }*A_{ 0042 }$ 这样的代码。以下代码使用命名字段完成工作,因此对于许多索引而言,它仍然可读:

idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))

I stumbled upon this problem when trying to print text, which I can copy paste into a Latex document. I extend on this answer and make use of named replacement fields:

Lets say you want to print out a product of mulitple variables with indices such as , which in Latex would be $A_{ 0042 }*A_{ 3141 }*A_{ 2718 }*A_{ 0042 }$ The following code does the job with named fields so that for many indices it stays readable:

idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))

回答 12

如果你想打印一个大括号(例如{),您可以使用{{,如果你愿意,你可以在后面的字符串添加多个支架。例如:

>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'

If you want to only print one curly brace (for example {) you can use {{, and you can add more braces later in the string if you want. For example:

>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'

回答 13

当您只是想插入代码字符串时,我建议您使用jinja2,它是Python的全功能模板引擎,即:

from jinja2 import Template

foo = Template('''
#include <stdio.h>

void main() {
    printf("hello universe number {{number}}");
}
''')

for i in range(2):
    print(foo.render(number=i))

因此,您不会因为其他答案而被迫复制花括号

When you’re just trying to interpolate code strings I’d suggest using jinja2 which is a full-featured template engine for Python, ie:

from jinja2 import Template

foo = Template('''
#include <stdio.h>

void main() {
    printf("hello universe number {{number}}");
}
''')

for i in range(2):
    print(foo.render(number=i))

So you won’t be enforced to duplicate curly braces as the whole bunch of other answers suggest


回答 14

您可以通过使用原始字符串方法来实现此目的,只需在字符串前添加不带引号的字符’r’。

# to print '{I am inside braces}'
print(r'{I am inside braces}')

You can do this by using raw string method by simply adding character ‘r’ without quotes before the string.

# to print '{I am inside braces}'
print(r'{I am inside braces}')