TypeError:-:"datetime.datetime"和"int"的不受支持的操作数类型 [英] TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'int'

查看:46
本文介绍了TypeError:-:"datetime.datetime"和"int"的不受支持的操作数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作天文钟,但在计算delta_time时遇到问题

I'm trying to build a chronometer but I'm having trouble calculating the delta_time

`def start():`
    start_time = datetime.datetime.now()
    print(start_time)

def stop():
    stop_time = datetime.datetime.now()
    print(stop_time)
    delta_time = stop_time - start_time

调用这些函数时,我得到:

When calling these functions i get:

2019-01-20 03:38:01.630833

2019-01-20 03:38:05.790672

File "test.py", line 15, in stop
    delta_time = stop_time - start_time
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'int'

我环顾四周,但没有发现任何有效的方法.我不知道是什么原因导致了这个问题.

I've looked around but found nothing that worked. I have no idea what might be causing this problem.

推荐答案

您显示的错误并不表示问题与变量范围有关,而是基于无法在非像类型.

The error you are showing doesn't indicate that the issue is with variable scope, rather it is encountered based on calculations not being able to be done on non-like types.

很难看到完整的代码,但是下面的内容可能会提供一种可能的替代解决方案:

It's difficult to say without seeing your full code, but perhaps the following will provide a possible alternative solution:

#!/usr/bin/env python

import datetime

def start():
    start_time = datetime.datetime.now()
    return start_time

def stop():
    stop_time = datetime.datetime.now()
    return stop_time

def delta(start,stop):
    delta_time = stop - start
    print(delta_time)

start=start()
stop=stop()
delta(start,stop)

此解决方案将两个生成的时间戳( start_time stop_time )移动到一个函数( delta )中作为参数,这样当 delta_time 是在其功能范围内对类似类型的变量进行的操作.

This solution moves the two generated timestamps (start_time and stop_time) into one single function (delta) as arguments so that when delta_time is calculated it is done on like-type variables within its function scope.

这篇关于TypeError:-:"datetime.datetime"和"int"的不受支持的操作数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆