Pergunta

Suppose I have this timestamp:

In [146]: t
Out[146]: datetime.time(11, 2, 5, 110521)

How do I convert this to the the number of seconds since midnight? One approach is to first convert this to a timedelta:

In [147]: datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second, microseconds=t.microsecond)
Out[147]: datetime.timedelta(0, 39725, 110521)

Then I can take the total_seconds(). But this seems really long-winded. Is there a more Pythonic way?

Foi útil?

Solução

Just multiply the hour and minute attributes, divide the microsecond attribute and add it all together:

>>> (t.hour * 3600) + (t.minute * 60) + t.second + (t.microsecond / 1000000.0)
39725.110521

You cannot use datetime.time.min because datetime.time objects don't support subtraction, unfortunately.

You could produce a datetime.datetime object by combining the time plus datetime.date.min (earliest supported date), then subtract datetime.datetime.min (earliest supported date and time), but that's long-winded too:

>>> datetime.datetime.combine(datetime.date.min, t) - datetime.datetime.min
datetime.timedelta(0, 39725, 110521)
>>> (datetime.datetime.combine(datetime.date.min, t) - datetime.datetime.min).total_seconds
39725.110521
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top