In Python, How to Convert a 'Datetime' Object to Seconds

In Python, how do you convert a `datetime` object to seconds?

For the special date of January 1, 1970 there are multiple options.

For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a timedelta object, which as of Python 2.7 has a total_seconds() function.

>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0

The starting date is usually specified in UTC, so for proper results the datetime you feed into this formula should be in UTC as well. If your datetime isn't in UTC already, you'll need to convert it before you use it, or attach a tzinfo class that has the proper offset.

As noted in the comments, if you have a tzinfo attached to your datetime then you'll need one on the starting date as well or the subtraction will fail; for the example above I would add tzinfo=pytz.utc if using Python 2 or tzinfo=timezone.utc if using Python 3.

How to convert a time object to seconds since midnight in python?

You could use datetime.combine() to create a datetime object, to get timedelta:

from datetime import datetime, timedelta

td = datetime.combine(datetime.min, t) - datetime.min
seconds = td.total_seconds() # Python 2.7+
integer_milliseconds = td // timedelta(milliseconds=1) # Python 3

It supports microseconds and any other future datetime.time.resolution.

Convert datetime format into seconds

Here's how you can do it:

>>> from datetime import datetime
>>> import time
>>> s = "16/08/2013 09:51:43"
>>> d = datetime.strptime(s, "%d/%m/%Y %H:%M:%S")
>>> time.mktime(d.timetuple())
1376632303.0

Also see Python Create unix timestamp five minutes in the future.

Obtaining total seconds from a datetime.time object

You can combine the time with a reference date to get a datetime object. If you then subtract that reference date, you get a timedelta object, from which you can take the total_seconds:

from datetime import datetime, time

t = time(2,0,0)

ts = (datetime.combine(datetime.min, t) - datetime.min).total_seconds()

print(ts)
# 7200.0

With pandas, I'd use the string representation of the time object column (Series) and convert it to timedelta datatype - which then allows you to use the dt accessor to get the total seconds:

import pandas as pd

df = pd.DataFrame({'time': [time(2,0,0)]})

df['totalseconds'] = pd.to_timedelta(df['time'].astype(str)).dt.total_seconds()

# df['totalseconds']
# 0 7200.0
# Name: totalseconds, dtype: float64

Convert date to seconds

AS far as I understand, UNIX represents the dates as the offset from Jan 1, 1970, so in order to do that in python you could get the time delta. In particular for your example:

from datetime import datetime
a = datetime.strptime(convdate, "%b %d %H:%M:%S %Y %Z")
b = datetime(1970, 1, 1)
(a-b).total_seconds()

The output is

1435752000.0

how to convert datetime object to time_ns

Since python 3.3 datetime has a timestamp function. Make sure to replace the timezone, otherwise local timezone will being taken and if you want to have nanosecond number you can multiply the seconds number.

from datetime import datetime; 
print(datetime(2022,2,22,15,41,50).replace(tzinfo=timezone.utc).timestamp()*10**9)

In Python, how do you convert seconds since epoch to a `datetime` object?

datetime.datetime.fromtimestamp will do, if you know the time zone, you could produce the same output as with time.gmtime

>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

or

>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)

Convert python datetime to timestamp in milliseconds

In Python 3 this can be done in 2 steps:

  1. Convert timestring to datetime object
  2. Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.

For example like this:

from datetime import datetime

dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
'%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000

print(millisec)

Output:

1482223122760.0

strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.

Here is the explanation of the format specifiers from the official documentation:

  • %d - Day of the month as a zero-padded decimal number.
  • %m - Month as a zero-padded decimal number.
  • %Y - Year with century as a decimal number
  • %H - Hour (24-hour clock) as a zero-padded decimal number.
  • %M - Minute as a zero-padded decimal number.
  • %S - Second as a zero-padded decimal number.
  • %f - Microsecond as a decimal number, zero-padded to 6 digits.


Related Topics



Leave a reply



Submit