简体   繁体   English

Python 字符串到 Django 时区(知道日期时间)

[英]Python string to Django timezone (aware datetime)

TL;DR;长话短说;博士;

How to convert 2016-01-01 to Django timezone ?如何将2016-01-01转换为 Django timezone

Full version :完整版

I receive a query string parameter from a form and I wanna get that string and use it as a datetime filter in Django.我从表单收到一个查询字符串参数,我想获取该字符串并将其用作 Django 中的日期时间过滤器。 The problem is that when I convert the string to a datetime, it's not making an aware datetime and so I lose a few hours due to timezone different.问题是,当我将字符串转换为日期时间时,它并没有意识到日期时间,因此由于时区不同,我损失了几个小时。 Maybe I'm losing myself in the formatting, but I'm not being able to do it.也许我在格式化中迷失了自己,但我做不到。

I have pytz, I have USE_TZ = True in my settings as well.我有 pytz,我的设置中也有USE_TZ = True

example:例子:

from datetime import date
# Example from what I receive as GET querystring parameter
start_date, end_date = '15-01-2016', '16-01-2016'
DATE_FORMAT = '%Y-%m-%d'
start_date = start_date.split('-')
start_date = date(int(start_date[2]), int(start_date[1]), int(start_date[0]))
sd_filter = start_date.strftime(DATE_FORMAT)

end_date = end_date.split('-')
end_date = date(int(end_date[2]), int(end_date[1]), int(end_date[0]))
ed_filter = end_date.strftime(DATE_FORMAT)

#query
my_list = MyModel.objects.filter(created_at__range=(sd_filter, ed_filter))

the problem lies in the filter.问题出在过滤器上。 I'm losing a few hours due to timezone from Django settings.由于 Django 设置的时区,我损失了几个小时。

UPDATE: I don't need to convert a datetime.now() to my time.更新:我不需要将datetime.now()转换为我的时间。 I need to convert a string to datetime.我需要将字符串转换为日期时间。

I know this is old but maybe will be helpful since I got into this situation as well:我知道这是旧的,但也许会有所帮助,因为我也遇到了这种情况:

What about using make_aware()?使用 make_aware() 怎么样?

from datetime import datetime
from django.utils.timezone import make_aware

date = '22-05-2018'
aware = make_aware(datetime.strptime(date, '%d-%m-%Y'))

This will use the currently active timezone (activated by timezone.activate ).这将使用当前活动的时区(由timezone.activate激活)。 If no timezone is activated explicitly, it would use the default timezone -- TIME_ZONE specified in settings.py .如果没有明确激活时区,它将使用默认时区——在settings.py中指定的TIME_ZONE

You are comparing time-zone unaware Python Date objects with the time-zone aware DateTimeField fields in your database.您正在将不了解时区的 Python Date对象与数据库中了解时区的DateTimeField字段进行比较。 It is probably more intuitive to use DateTime objects - and these can be made time-zone aware easily as follows:使用DateTime对象可能更直观 - 这些对象可以很容易地识别时区,如下所示:

import datetime
import pytz

start_date = '15-01-2016' 
end_date = '16-01-2016'
date_format = '%d-%m-%Y'

unaware_start_date = datetime.datetime.strptime(start_date, date_format)
aware_start_date = pytz.utc.localize(unaware_start_date)

unaware_end_date = datetime.datetime.strptime(end_date, date_format)
aware_end_date = pytz.utc.localize(unaware_end_date)

my_list = MyModel.objects.filter(created_at__range=(aware_start_date, aware_end_date))

This creates unaware_start_date and unaware_end_date DateTime objects using strptime() .这将使用strptime()创建unaware_start_dateunaware_end_date DateTime对象。 It then uses pytz.utc.localize to make the objects time-zone aware (you will need to replace utc with your relevant time-zone).然后它使用pytz.utc.localize使对象具有时区意识(您需要将utc替换为您的相关时区)。

You can then have time-zone aware DateTime objects - aware_start_date and aware_end_date .然后,您可以拥有时区感知DateTime对象 - aware_start_dateaware_end_date Feeding these into your filter should yield the desired results.将这些输入过滤器应该会产生预期的结果。

from django.utils import timezone
timestamp_raw = timezone.now() #current time, or use whatever time you have
date_format = '%Y-%m-%d %H:%M:%S' #time format day-month-year hour:minutes:seconds
timestamp = timezone.datetime.strftime(timestamp_raw, date_format)

Or Using the new f-string formatter或者使用新的 f-string 格式化程序

f"{timezone:%Y-%m-%d %H:%M:%S %p}"

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

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