0

I would like to get the difference between the start of a date with any other time in that date

For example

y = datetime.datetime(2012,1,1,1,1,1)

time_delta_in_seconds = (y.time()-datetime.time(0,0,0)).total_seconds()

However I got the following error

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time

Are there ways to accomplish my goal?

Kevin
  • 2,187
  • 4
  • 26
  • 35
  • what answer do you want to get if there is a DST transition between the given time and midnight (start of a day)? If you want to get the number of *elapsed* seconds since midnight; you need to take into the account the corresponding timezone. See [Find if 24 hrs have passed between datetimes](http://stackoverflow.com/q/26313520/4279) – jfs Dec 22 '14 at 02:33
  • see also, [How do I get the UTC time of “midnight” for a given timezone?](http://stackoverflow.com/a/11236372/4279), and [Python: Given the current time in UTC, how do you determine the start and end time of the day in a particular timezone?](http://stackoverflow.com/a/25605133/4279) – jfs Dec 22 '14 at 02:48

1 Answers1

3

You can use the combine method to build a new datetime whose hours, minutes, seconds (and microseconds) are set to 0. The difference of two datetimes is a timedelta, which has the total_seconds method.

In [80]: import datetime as DT
In [81]: y = DT.datetime(2012,1,1,1,1,1)

In [82]: z = DT.datetime.combine(y, DT.time(0))
In [84]: z
Out[84]: datetime.datetime(2012, 1, 1, 0, 0)

In [83]: (y - z).total_seconds()
Out[83]: 3661.0
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677