Python-datetime.now()返回不正确的时间 [英] Python - datetime.now() returns incorrect time

查看:1046
本文介绍了Python-datetime.now()返回不正确的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将操作的时间戳记存储在数据库中。问题是我从 datetime.datetime.now()获得的时间不正确(我猜是由于时区)。我尝试使用python在终端中获取值并获得正确的结果。

I want to store in my data base the time stamp of an operation. The problem is that the time that I get from datetime.datetime.now()is incorrect (I guess it's due to time zone). I tried getting the value in the terminal using python and got the correct result.

import datetime 
datetime.datetime.now()//correct time

但是,如果我在执行问题期间打印结果,则输出不正确,结果早了两个小时。

However if I print the result during problem execution the output is incorrect, the result is two hours earlier.

为什么会这样,终端给了我正确的时间,但是程序实例却没有,我如何获得正确的时间我的程序中的时间?

Why is it like that, that the terminal gives me the correct time but the program instance isn't, how can I get the correct time in my program?

编辑:
来自终端的日期时间:

The date time from the terminal:

2018-08-30 17:41:04.413187

日期从程序实例开始的时间:

The date time from program instance:

2018-08-30 14:42:31.761310

编辑:

我注意到当我收到此警告时我运行程序。

I noticed that I have this warning when I run the program.

RuntimeWarning: DateTimeField Policy.last_update received a naive datetime (2018-08-30 15:16:23.689896) while time zone support is active.
  RuntimeWarning)


推荐答案

尝试调整数字小时数,具体取决于您所在的时区:

Try this adjusting the number of hours depending on the timezone you are:

import datetime 

datetime.datetime.utcnow()+datetime.timedelta(hours=3)

这篇关于Python-datetime.now()返回不正确的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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