Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
DjangogirlsTutorialに出てくるtimezone.nowの秘密
Search
mizzsugar
November 16, 2019
Programming
400
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
DjangogirlsTutorialに出てくるtimezone.nowの秘密
mizzsugar
November 16, 2019
More Decks by mizzsugar
See All by mizzsugar
自分のPCにPython環境を用意して_VSCodeでStreamlitアプリを動かすまでの8ステップ.pdf
mizzsugar
0
130
Colabのみで初心者向けPythonハンズオン.pdf
mizzsugar
0
95
厳しさとゆるさの間で迷う人に捧げる個人開発記
mizzsugar
0
76
SQLModel入門〜クエリと型〜
mizzsugar
3
1.6k
フルリモート向いてないと思っていた私が、なんだかんだ健やかに 1年半フルリモート出来ている話
mizzsugar
1
170
Djangoでのプロジェクトだって型ヒントを運用出来る!
mizzsugar
4
9.2k
「動くものは作れる」の一歩先へ 〜「自走プログラマー」の紹介〜
mizzsugar
0
670
pytestの第一歩 〜「テスト駆動Python」の紹介〜
mizzsugar
3
500
データ分析ツール開発でpoetryを使う選択肢
mizzsugar
1
1.2k
Other Decks in Programming
See All in Programming
Unity6 URPによる海底をテーマにしたVJシステムの解説 | Unity Shader 完全に理解した 勉強会
gam0022
0
370
Simple Storage Service(S3) is not simple
iwatsukayura
0
290
AIに “答え“を書かせるのを やめてみた
___akari11
0
120
Starting & Sustaining Code-Based E2E Testing for Non-Coding QA Teams( #jasstniigata )
teyamagu
PRO
1
1k
ハーネス設計入門 〜 基礎知識の整理から実務へのステップアップ 〜
kinopeee
28
32k
Domain-Driven Transformation
hschwentner
2
2.3k
JAWS-UG 東京支部が始める、JAWS-UG支部コラボ / JAWS-UG lunchtime LT Collaboration
y0hgi
0
270
Long Living Tokens, Die, Die, Die! (or: The One Ring is Banned in Modern)
sylph01
0
300
AWSに止められる覚悟してますか?
morizo_1984
2
530
Findy - エンジニア向け会社紹介/Findy Company Deck
findyinc
6
400k
iOS 27でニュースアプリはどう変わる!? 〜日経電子版の新機能対応と、開発事例から〜
lynnswap
7
13k
Kotlinの15年とServer-Side Kotlin
n_takehata
1
150
Featured
See All Featured
Collaborative Software Design: How to facilitate domain modelling decisions
baasie
1
340
Bioeconomy Workshop: Dr. Julius Ecuru, Opportunities for a Bioeconomy in West Africa
akademiya2063
PRO
1
410
Money Talks: Using Revenue to Get Sh*t Done
nikkihalliwell
0
520
A better future with KSS
kneath
240
18k
Mind Mapping
helmedeiros
1
400
Tell your own story through comics
letsgokoyo
1
1.1k
The World Runs on Bad Software
bkeepers
PRO
72
12k
A Guide to Academic Writing Using Generative AI - A Workshop
ks91
PRO
1
520
How to Build an AI Search Optimization Roadmap - Criteria and Steps to Take #SEOIRL
aleyda
1
2.2k
Designing for Performance
lara
612
70k
What’s in a name? Adding method to the madness
productmarketing
PRO
24
4.2k
Writing Fast Ruby
sferik
630
63k
Transcript
DjangogirlsTutorialに出てくる timezone.nowの秘密 2019/11/16 Djangogirls @mizzsugar0425
お前、誰よ • みずきと申します。 • やっていること↓ ◦ 昼:データ分析のデータ基盤のデータマネジメント (GCP: 特にBigQuery) ◦
夜:PythonでWebアプリ開発(Pyramid, PostgreSQL, Nuxt.js, TypeScript) ◦ つい最近まで仕事で Djagoいじってたので趣味で Django触ったりもします ◦ Twitter -> @mizzsugar0425 • コーヒーと自転車が好き
DjangogirlsTutorialの復習をしていたときのこと
しれっと使ってるdjango.utils.timezone.now from django.conf import settings from django.db import models from
django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() https://tutorial.djangogirls.org/ja/django_models/ timezone.nowは 現在の日時を返すよ
なぜPython標準ライブラリの datetime.datetime.nowではないの? datetime.datetime.nowも 現在の日時を返すのに!!
秘密はここにあった! USE_TZ = True settings.py
USE_TZ=Trueだとタイムゾーンサポートが有効 今19時 だよー 今10時 だよー
タイムゾーンサポートがあるなら settings.pyで TIMEZONE = ‘Asia/Tokyo’と設定している場合・・・ • テンプレート上で日本時間を表示してくれて便利! • settings.pyのTIMEZONEを変更したらその場所の現地時間を表示 •
複数のタイムゾーンを使う場合、どのタイムゾーンの時間を表示するか設定す ればどのタイムゾーンの時間を表示するかそれぞれ振り分けてくれる※ ※公式ドキュメントにタイムゾーンを選択して表示するための実装例があります ↓ https://docs.djangoproject.com/ja/2.2/topics/i18n/timezones/#selecting-the-current-time-zone
内部ではどうなっているの? >>> from django.contrib.auth.models import User >>> from blog.models import
Post >>> >>> author = User.objects.create(username='dummy', email='
[email protected]
') >>> post = Post.objects.create( author=author, title='dummy', text='dummy' ) >>> post.publish() # 日本時間で2019/10/10 19:00:00に実行 >>> post.published_date datetime.datetime(2019, 10, 10, 10, 0, 0, tzinfo=<UTC>) 19時じゃない! UTCって!? を実行したら・・・ python manage.py shell
前提知識:nativeとawareという概念 ざっくりPythonでは 日時を扱うdatetimeモジュールのdatetimeオブジェクトを • タイムゾーンなしのdatetimeオブジェクトはnative ex: datetime.datetime(2019, 10, 10, 19,
0, 0) • タイムゾーンありのdatetimeオブジェクトはaware ex: datetime.datetime(2019, 10, 10, 19, 0, 0, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>) と分けている もっと詳しい説明は公式ドキュメントで ↓ https://docs.python.org/ja/3/library/datetime.html#aware-and-naive-objects
UTCとは • 協定世界時(Coordinated Universal Time)のこと • 今の世界で標準時として使っている時間のこと • 日本の場合だと、世界の標準時間より9時間早い https://wa3.i-3-i.info/word11831.html
内部的な話 使う場所 表示形式 表示例 (日本時間2019/10/10 19時を例に) テンプレート・フォーム 現地時間(日本なら日本時間) テンプレート:2019年10月10日 19時0分0秒
フォーム: datetime.datetime(2019, 10, 10, 19, 0, 0, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>) 内部の処理 UTC時間 datetime.datetime(2019, 10, 10, 10, 0, 0, tzinfo=<UTC>) データベース タイムゾーンなしの時間 (値としてはUTCでの時間) 2019-10-10 10:00:00 ※PostgreSQLだと 2019-10-10 10:00:00+00
1つのタイムゾーンでしか使わなくても • native -> awareに変換した際に意図しない値に変換してしまうバグを防げる • Djangoがawareなdatetimeオブジェクトを想定している処理でnativeなオブジェ クトを使うことによるバグを防げる • django-admin
startprojectコマンドで作られるプロジェクトでタイムゾーンサ ポートありになっていることからもタイムゾーンサポートありの方がいいと主張し ていることがうかがえる
datetime.datetime.nowの話に戻ると・・・ >>> from django.utils import timezone >>> import datetime >>>
>>> from django.utils import timezone >>> >>> # nativeなdatetimeオブジェクト >>> datetime.datetime.now() datetime.datetime(2019, 11, 12, 18, 0, 39, 452139) >>> >>> # タイムゾーンがUTCであるawareなdatetimeオブジェクト >>> timezone.now() datetime.datetime(2019, 11, 12, 9, 0, 46, 708708, tzinfo=<UTC>)
USE_TZ=Trueでnativeなオブジェクトを使うと RuntimeWarning: DateTimeField received a naive datetime * to while
time zone support is active. Djangoから「タイムゾーンサポートが有効な時にnativeなdatetimeオブジェク トを使わないでください」と注意されます。 エラーやワーニングは意地悪じゃなくて 安全なシステムを作るための優しさで 出来ているよ。
つまりdatetime.datetime.nowは使わない訳は タイムゾーンサポートが有効な設定をしているから 使っても動きはするけれども native -> awareの変換周りで苦労するやも
まとめ • Pythonのdatetimeオブジェクトにはnativeとawareという概念があり、前者 がタイムゾーンなしで後者がタイムゾーンありの日時(ざっくり) • Djangoではタイムゾーンサポートを有効にした方が安全 • タイムゾーンサポートを有効にした場合、Djangoでは内部的な処理ではタ イムゾーンがUTCの日時を使い、画面やフォームで現地時間に柔軟に変 換できるようにしている
• エラーやワーニングは意地悪じゃなくて優しさ
ありがとうございました!