How To Remove Date From Datetime Object
I have a method that converts a string to a datetime object using
strptime("%I:%M %p"), I only want the hours in 24 and minutes without any dates, because I will get the difference between this time and another time. The problem is that when I try to get the difference with
total_seconds(), it gets difference in negative because the date in the strptime is "1900-01-01". Does any one have any ideas how to solve this?
fTime = datetime.strptime(time, "%I:%M %p") if 0 < (fTime - datetime.now()).total_seconds() <= 3600: return True
You can take one of two approaches: strip the date out of
now, or add the current date to
fTime. The first approach makes little sense, since you can't compare
time objects like that anyway.
fDate = datetime.combine(date.today(), fTime.time()) return 0 < (fDate - datetime.now()).total_seconds() <= 3600
Alternatively, you can
replace the date portion:
today = date.today() fDate = fTime.replace(year=today.year, month=today.month, day=today.day)
Personally, I would go with
combine because it's less awkward code.
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module