Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

python - datetime.now() gets different time than the one my pc has configured

I've been looking through this sites posts on this issue i have, and none of them solve my problem so far. What happens is that my datetime.now() method from datetime module doesnt show time as configured in my pc, so here i did some tests in order to figure out what's happening. a few minutes ago I solved it by specifying the timezone through dateutil module, but it shouldn't be done in that way.

Note: I'm currently using Ubuntu/Linux OS, and use a virtual environment for my project.

CODE:

from dateutil import tz
from datetime import date, datetime, time

date1 = datetime.now(tz.tzlocal()) # it works not at all
date1_ = datetime.now() # Same thing
date2 = datetime.now(tz.gettz('Cuba')) # it does now
date1_tz_info = date1.timetz()
print(date1, date1_, date2, sep='
')
print(date1_tz_info)

OUTPUT:

  1. 2021-01-19 22:39:13.960834+00:00
  2. 2021-01-19 22:39:13.960874
  3. 2021-01-19 17:39:13.961087-05:00 #The Right Output
  4. 22:39:13.960834+00:00

Picture from pc

So as far as seen now datetime.now() returns value as if it was utc +00:00.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Python 3.x, local timezone can be figured out like this:

import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo

if the python version is before 3.6 you can use

import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo

From that we can see which timezone python thinks is local. How to change the time zones for windows 10 is below

In windows command prompt try:

This gives current timezone:

tzutil /g

This gives a list of timezones:

tzutil /l

This will set the timezone:

tzutil /s "Central America Standard Time"

For further reference: http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...