Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Stéphane Diez
Stéphane Diez
19,350 Points

how to convert datetime in python

In my python script I want to save the time like this:

start_time = datetime.now()

How can I make this start_time that it shows me how much seconds , minutes I have , I mean it's possible to do a total_seconds() or something?=

I want to convert this : datetime.now() in seconds only.

It's not entirely clear in your question what you're trying to do. Could you possibly rephrase or elaborate a bit?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

A datetime is a time object. The "number of seconds" needs to be relative to some other time. if using datetime.second you'll get the number of seconds into this datetime's minute.

If you want the difference between two datetime objects, you can subtract them to get a timedelta object that has a total_seconds() method:

$  python
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import time
>>> now1 = datetime.datetime.now()
>>> time.sleep(10)
>>> now2 = datetime.datetime.now()
>>> (now2 - now1).total_seconds()
16.014057
>>> 

Using this answer from StackOverflow, you can get the seconds since the epoch (1 Jan 1970):

>>> epoch = datetime.datetime.utcfromtimestamp(0)
>>> seconds_since_epoch = (datetime.datetime.now() - epoch).total_seconds()
>>> seconds_since_epoch
1467410206.475112