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
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
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
140
Colabのみで初心者向けPythonハンズオン.pdf
mizzsugar
0
100
厳しさとゆるさの間で迷う人に捧げる個人開発記
mizzsugar
0
77
SQLModel入門〜クエリと型〜
mizzsugar
3
1.7k
フルリモート向いてないと思っていた私が、なんだかんだ健やかに 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
Zero-Tap Sign-In対応、結局何をすればいいの?
mitohato14
0
1.1k
LLM 101
dalinaum
0
260
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
490
graphql-ruby を Spinel で速くしようとした話
mtsmfm
0
130
React Native에 현대적인 빌드 도구 더하기: Rollipop 구현기
leegeunhyeok
0
160
Performance Optimization With LLMs
xleitix
0
230
우리의 Nitro Modules는 당신의 Turbo Modules보다 아름답다
l2hyunwoo
0
240
続・コーディングルールの鮮度を保ちたい / keep-fresh-go-internal-conventions-again
handlename
0
150
선언형 햅틱 라이브러리 진동을 소개합니다
l2hyunwoo
1
110
Herb in Rails 8.2: Your ERB views, now HTML-aware @ Kaigi on Rails 2026, Tokyo, Japan
marcoroth
2
370
Web Framework Benchmark Battle 2026, Any%
a_matsuda
3
3.1k
SFCで実現する病院・医療システムの動的組み立て式UI
koukimiura
1
140
Featured
See All Featured
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
194
17k
Building Adaptive Systems
keathley
44
3.3k
The Straight Up "How To Draw Better" Workshop
denniskardys
239
140k
Designing for Performance
lara
612
70k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4.6k
Getting science done with accelerated Python computing platforms
jacobtomlinson
2
560
More Than Pixels: Becoming A User Experience Designer
marktimemedia
3
600
Sam Torres - BigQuery for SEOs
techseoconnect
PRO
0
590
SEO for Brand Visibility & Recognition
aleyda
0
4.8k
From π to Pie charts
rasagy
1
420
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
35
2.6k
SEO in 2025: How to Prepare for the Future of Search
ipullrank
3
3.9k
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の日時を使い、画面やフォームで現地時間に柔軟に変 換できるようにしている
• エラーやワーニングは意地悪じゃなくて優しさ
ありがとうございました!