Categories
Python Answers

How to convert a datetime object to seconds with Python?

Spread the love

Sometimes, we want to convert a datetime object to seconds with Python.

In this article, we’ll look at how to convert a datetime object to seconds with Python.

How to convert a datetime object to seconds with Python?

To convert a datetime object to seconds with Python, we can use the datetime timestamp method.

For instance, we write

from datetime import datetime

dt = datetime.today()
seconds = dt.timestamp()

to get today’s datetime with datetime.today.

Then we call timestamp on the returned datetime object to get the timestamp of it in seconds.

Conclusion

To convert a datetime object to seconds with Python, we can use the datetime timestamp method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *