简体   繁体   English

服务器python中的确切时间

[英]Exact time in server python

I've a script that read a db and send sms to user in a specific time, my server is in london and my country Guatemala is (-6 Hours), i use: 我有一个脚本读取数据库并在特定时间向用户发送短信,我的服务器在伦敦,我的国家危地马拉是(-6小时),我使用:

local_time = datetime.datetime.utcnow() + datetime.timedelta(hours=-6)

I'm afraid of Daylight could change and my sms is send incorrectly 我担心Daylight会改变,我的短信发送错误

Is there any way to control this? 有没有办法控制这个?

You can use a library such as pytz to check the local time instead 您可以使用诸如pytz的库来检查当地时间

>>> from pytz import timezone
>>> tz= timezone('America/Guatemala')
>>> from datetime import datetime
>>> tz.fromutc( datetime.utcnow() )
datetime.datetime(2014, 4, 22, 12, 4, 37, 2229, tzinfo=<DstTzInfo 'America/Guatemala' CST-1 day, 18:00:00 STD>)

The accuracy of the library is as good as the accuracy of the underlying timezone database, so if it doesn't suit your purposes, please consider contributing to it. 库的准确性与基础时区数据库的准确性一样好,因此如果它不适合您的目的,请考虑为此做出贡献。

To get the current time in a given timezone: 要获得给定时区的当前时间:

from datetime import datetime
import pytz # $ pip install pytz

now = datetime.now(pytz.timezone('America/Guatemala'))

Example: 例:

>>> print(now.strftime('%F %T %Z%z'))
2014-04-23 01:04:46 CST-0600

On *nix with tz database you could change your local timezone (stdlib-only solution): 在带有tz数据库的* nix上,您可以更改本地时区(仅限stdlib的解决方案):

import os
import time
from datetime import datetime, timezone

os.environ['TZ'] = ':America/Guatemala'
time.tzset()

# to get local time
print(datetime.now(timezone.utc).astimezone().strftime('%F %T %Z%z'))
# -> 2014-04-23 01:12:38 CST-0600

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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