简体   繁体   中英

Figuring out usage of datetime module

Just learning to code with python to scratch an itch.

I've been using a program on my phone which tells me how many days it is since my last cigarette. I want to be able to show that same thing in moments on my desktop and google indicated that the datetime module would be useful for this.

I have sussed out (and I'm proud of myself for this as I'm only just learning) how to get dates into variables and how to subtract the date of my last smoke from the current date. What I can't figure out from the module page on the python docs is how to truncate that result so that it only shows the number of days. Currently it shows the number and follows it with a number of hours and seconds.

What I've got so far:

#importing module and functions from that module
import datetime

from datetime import date
from datetime import timedelta

#define dates and put today into a variable

today = date.today()
smokequit = datetime.date(2011, 1, 30)

#do the maths

nosmoke = today - smokequit

#output the number of days

print ("No cigarettes for ", nosmoke, "days")

This gives me:

"No cigarettes for 3442 days, 0:00:00 days"

How do I get rid of the last part so I only have the number of days?

Many thanks in advance.

EDIT:

Thanks to the responses, I figured the answer out.

print ("No cigarettes for ", nosmoke.days, " days") 

You can do this (Just replace this in your code accordingly)

# grab number of days
nosmoke = str((today - smokequit).days)

# output the number of days
print("No cigarettes for ", nosmoke)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM