summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fdatetime.html
blob: 9fcc6aeefc548a8ada810970242cad28fb370f7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
 <span id="datetime-basic-date-and-time-types"></span><h1>datetime — Basic date and time types</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/datetime.py">Lib/datetime.py</a></p>  <p>The <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code>datetime</code></a> module supplies classes for manipulating dates and times.</p> <p>While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.</p> <div class="admonition tip"> <p class="admonition-title">Tip</p> <p>Skip to <a class="reference internal" href="#format-codes"><span class="std std-ref">the format codes</span></a>.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
<code>Module</code> <a class="reference internal" href="calendar#module-calendar" title="calendar: Functions for working with calendars, including some emulation of the Unix cal program."><code>calendar</code></a>
</dt>
<dd>
<p>General calendar related functions.</p> </dd> <dt>
<code>Module</code> <a class="reference internal" href="time#module-time" title="time: Time access and conversions."><code>time</code></a>
</dt>
<dd>
<p>Time access and conversions.</p> </dd> <dt>
<code>Module</code> <a class="reference internal" href="zoneinfo#module-zoneinfo" title="zoneinfo: IANA time zone support"><code>zoneinfo</code></a>
</dt>
<dd>
<p>Concrete time zones representing the IANA time zone database.</p> </dd> <dt>Package <a class="reference external" href="https://dateutil.readthedocs.io/en/stable/">dateutil</a>
</dt>
<dd>
<p>Third-party library with expanded time zone and parsing support.</p> </dd> <dt>Package <a class="reference external" href="https://pypi.org/project/datetype/">DateType</a>
</dt>
<dd>
<p>Third-party library that introduces distinct static types to e.g. allow <a class="reference internal" href="../glossary#term-static-type-checker"><span class="xref std std-term">static type checkers</span></a> to differentiate between naive and aware datetimes.</p> </dd> </dl> </div> <section id="aware-and-naive-objects"> <span id="datetime-naive-aware"></span><h2>Aware and Naive Objects</h2> <p>Date and time objects may be categorized as “aware” or “naive” depending on whether or not they include timezone information.</p> <p>With sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, an <strong>aware</strong> object can locate itself relative to other aware objects. An aware object represents a specific moment in time that is not open to interpretation. <a class="footnote-reference brackets" href="#id5" id="id1">1</a></p> <p>A <strong>naive</strong> object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it is up to the program whether a particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.</p> <p>For applications requiring aware objects, <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> and <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> objects have an optional time zone information attribute, <code>tzinfo</code>, that can be set to an instance of a subclass of the abstract <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> class. These <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> objects capture information about the offset from UTC time, the time zone name, and whether daylight saving time is in effect.</p> <p>Only one concrete <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> class, the <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a> class, is supplied by the <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code>datetime</code></a> module. The <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a> class can represent simple timezones with fixed offsets from UTC, such as UTC itself or North American EST and EDT timezones. Supporting timezones at deeper levels of detail is up to the application. The rules for time adjustment across the world are more political than rational, change frequently, and there is no standard suitable for every application aside from UTC.</p> </section> <section id="constants"> <h2>Constants</h2> <p>The <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code>datetime</code></a> module exports the following constants:</p> <dl class="py data"> <dt class="sig sig-object py" id="datetime.MINYEAR">
<code>datetime.MINYEAR</code> </dt> <dd>
<p>The smallest year number allowed in a <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> or <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object. <a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code>MINYEAR</code></a> is <code>1</code>.</p> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="datetime.MAXYEAR">
<code>datetime.MAXYEAR</code> </dt> <dd>
<p>The largest year number allowed in a <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> or <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object. <a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code>MAXYEAR</code></a> is <code>9999</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.UTC">
<code>datetime.UTC</code> </dt> <dd>
<p>Alias for the UTC timezone singleton <a class="reference internal" href="#datetime.timezone.utc" title="datetime.timezone.utc"><code>datetime.timezone.utc</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
</dl> </section> <section id="available-types"> <h2>Available Types</h2> <dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-prename descclassname">datetime.</span><span class="sig-name descname">date</span>
</dt> <dd>
<p>An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: <a class="reference internal" href="#datetime.date.year" title="datetime.date.year"><code>year</code></a>, <a class="reference internal" href="#datetime.date.month" title="datetime.date.month"><code>month</code></a>, and <a class="reference internal" href="#datetime.date.day" title="datetime.date.day"><code>day</code></a>.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-prename descclassname">datetime.</span><span class="sig-name descname">time</span>
</dt> <dd>
<p>An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. (There is no notion of “leap seconds” here.) Attributes: <a class="reference internal" href="#datetime.time.hour" title="datetime.time.hour"><code>hour</code></a>, <a class="reference internal" href="#datetime.time.minute" title="datetime.time.minute"><code>minute</code></a>, <a class="reference internal" href="#datetime.time.second" title="datetime.time.second"><code>second</code></a>, <a class="reference internal" href="#datetime.time.microsecond" title="datetime.time.microsecond"><code>microsecond</code></a>, and <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code>tzinfo</code></a>.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-prename descclassname">datetime.</span><span class="sig-name descname">datetime</span>
</dt> <dd>
<p>A combination of a date and a time. Attributes: <a class="reference internal" href="#datetime.datetime.year" title="datetime.datetime.year"><code>year</code></a>, <a class="reference internal" href="#datetime.datetime.month" title="datetime.datetime.month"><code>month</code></a>, <a class="reference internal" href="#datetime.datetime.day" title="datetime.datetime.day"><code>day</code></a>, <a class="reference internal" href="#datetime.datetime.hour" title="datetime.datetime.hour"><code>hour</code></a>, <a class="reference internal" href="#datetime.datetime.minute" title="datetime.datetime.minute"><code>minute</code></a>, <a class="reference internal" href="#datetime.datetime.second" title="datetime.datetime.second"><code>second</code></a>, <a class="reference internal" href="#datetime.datetime.microsecond" title="datetime.datetime.microsecond"><code>microsecond</code></a>, and <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a>.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-prename descclassname">datetime.</span><span class="sig-name descname">timedelta</span>
</dt> <dd>
<p>A duration expressing the difference between two <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a>, <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a>, or <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> instances to microsecond resolution.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-prename descclassname">datetime.</span><span class="sig-name descname">tzinfo</span>
</dt> <dd>
<p>An abstract base class for time zone information objects. These are used by the <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> and <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> classes to provide a customizable notion of time adjustment (for example, to account for time zone and/or daylight saving time).</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-prename descclassname">datetime.</span><span class="sig-name descname">timezone</span>
</dt> <dd>
<p>A class that implements the <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> abstract base class as a fixed offset from the UTC.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <p>Objects of these types are immutable.</p> <p>Subclass relationships:</p> <pre data-language="python">object
    timedelta
    tzinfo
        timezone
    time
    date
        datetime
</pre> <section id="common-properties"> <h3>Common Properties</h3> <p>The <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a>, <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a>, <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a>, and <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a> types share these common features:</p> <ul class="simple"> <li>Objects of these types are immutable.</li> <li>Objects of these types are <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a>, meaning that they can be used as dictionary keys.</li> <li>Objects of these types support efficient pickling via the <a class="reference internal" href="pickle#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code>pickle</code></a> module.</li> </ul> </section> <section id="determining-if-an-object-is-aware-or-naive"> <h3>Determining if an Object is Aware or Naive</h3> <p>Objects of the <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> type are always naive.</p> <p>An object of type <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> or <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> may be aware or naive.</p> <p>A <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object <em>d</em> is aware if both of the following hold:</p> <ol class="arabic simple"> <li>
<code>d.tzinfo</code> is not <code>None</code>
</li> <li>
<code>d.tzinfo.utcoffset(d)</code> does not return <code>None</code>
</li> </ol> <p>Otherwise, <em>d</em> is naive.</p> <p>A <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object <em>t</em> is aware if both of the following hold:</p> <ol class="arabic simple"> <li>
<code>t.tzinfo</code> is not <code>None</code>
</li> <li>
<code>t.tzinfo.utcoffset(None)</code> does not return <code>None</code>.</li> </ol> <p>Otherwise, <em>t</em> is naive.</p> <p>The distinction between aware and naive doesn’t apply to <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> objects.</p> </section> </section> <section id="timedelta-objects"> <span id="datetime-timedelta"></span><h2>timedelta Objects</h2> <p>A <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object represents a duration, the difference between two dates or times.</p> <dl class="py class"> <dt class="sig sig-object py" id="datetime.timedelta">
<code>class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)</code> </dt> <dd>
<p>All arguments are optional and default to <code>0</code>. Arguments may be integers or floats, and may be positive or negative.</p> <p>Only <em>days</em>, <em>seconds</em> and <em>microseconds</em> are stored internally. Arguments are converted to those units:</p> <ul class="simple"> <li>A millisecond is converted to 1000 microseconds.</li> <li>A minute is converted to 60 seconds.</li> <li>An hour is converted to 3600 seconds.</li> <li>A week is converted to 7 days.</li> </ul> <p>and days, seconds and microseconds are then normalized so that the representation is unique, with</p> <ul class="simple"> <li><code>0 &lt;= microseconds &lt; 1000000</code></li> <li>
<code>0 &lt;= seconds &lt; 3600*24</code> (the number of seconds in one day)</li> <li><code>-999999999 &lt;= days &lt;= 999999999</code></li> </ul> <p>The following example illustrates how any arguments besides <em>days</em>, <em>seconds</em> and <em>microseconds</em> are “merged” and normalized into those three resulting attributes:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import timedelta
&gt;&gt;&gt; delta = timedelta(
...     days=50,
...     seconds=27,
...     microseconds=10,
...     milliseconds=29000,
...     minutes=5,
...     hours=8,
...     weeks=2
... )
&gt;&gt;&gt; # Only days, seconds, and microseconds remain
&gt;&gt;&gt; delta
datetime.timedelta(days=64, seconds=29156, microseconds=10)
</pre> <p>If any argument is a float and there are fractional microseconds, the fractional microseconds left over from all arguments are combined and their sum is rounded to the nearest microsecond using round-half-to-even tiebreaker. If no argument is a float, the conversion and normalization processes are exact (no information is lost).</p> <p>If the normalized value of days lies outside the indicated range, <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a> is raised.</p> <p>Note that normalization of negative values may be surprising at first. For example:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import timedelta
&gt;&gt;&gt; d = timedelta(microseconds=-1)
&gt;&gt;&gt; (d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)
</pre> </dd>
</dl> <p>Class attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.timedelta.min">
<code>timedelta.min</code> </dt> <dd>
<p>The most negative <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object, <code>timedelta(-999999999)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.timedelta.max">
<code>timedelta.max</code> </dt> <dd>
<p>The most positive <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object, <code>timedelta(days=999999999,
hours=23, minutes=59, seconds=59, microseconds=999999)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.timedelta.resolution">
<code>timedelta.resolution</code> </dt> <dd>
<p>The smallest possible difference between non-equal <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> objects, <code>timedelta(microseconds=1)</code>.</p> </dd>
</dl> <p>Note that, because of normalization, <code>timedelta.max</code> &gt; <code>-timedelta.min</code>. <code>-timedelta.max</code> is not representable as a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object.</p> <p>Instance attributes (read-only):</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Attribute</p></th> <th class="head"><p>Value</p></th> </tr> </thead>  <tr>
<td><p><code>days</code></p></td> <td><p>Between -999999999 and 999999999 inclusive</p></td> </tr> <tr>
<td><p><code>seconds</code></p></td> <td><p>Between 0 and 86399 inclusive</p></td> </tr> <tr>
<td><p><code>microseconds</code></p></td> <td><p>Between 0 and 999999 inclusive</p></td> </tr>  </table> <p>Supported operations:</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Operation</p></th> <th class="head"><p>Result</p></th> </tr> </thead>  <tr>
<td><p><code>t1 = t2 + t3</code></p></td> <td><p>Sum of <em>t2</em> and <em>t3</em>. Afterwards <em>t1</em>-<em>t2</em> == <em>t3</em> and <em>t1</em>-<em>t3</em> == <em>t2</em> are true. (1)</p></td> </tr> <tr>
<td><p><code>t1 = t2 - t3</code></p></td> <td><p>Difference of <em>t2</em> and <em>t3</em>. Afterwards <em>t1</em> == <em>t2</em> - <em>t3</em> and <em>t2</em> == <em>t1</em> + <em>t3</em> are true. (1)(6)</p></td> </tr> <tr>
<td><p><code>t1 = t2 * i or t1 = i * t2</code></p></td> <td><p>Delta multiplied by an integer. Afterwards <em>t1</em> // i == <em>t2</em> is true, provided <code>i != 0</code>.</p></td> </tr> <tr>
<td></td> <td><p>In general, <em>t1</em> * i == <em>t1</em> * (i-1) + <em>t1</em> is true. (1)</p></td> </tr> <tr>
<td><p><code>t1 = t2 * f or t1 = f * t2</code></p></td> <td><p>Delta multiplied by a float. The result is rounded to the nearest multiple of timedelta.resolution using round-half-to-even.</p></td> </tr> <tr>
<td><p><code>f = t2 / t3</code></p></td> <td><p>Division (3) of overall duration <em>t2</em> by interval unit <em>t3</em>. Returns a <a class="reference internal" href="functions#float" title="float"><code>float</code></a> object.</p></td> </tr> <tr>
<td><p><code>t1 = t2 / f or t1 = t2 / i</code></p></td> <td><p>Delta divided by a float or an int. The result is rounded to the nearest multiple of timedelta.resolution using round-half-to-even.</p></td> </tr> <tr>
<td><p><code>t1 = t2 // i</code> or <code>t1 = t2 // t3</code></p></td> <td><p>The floor is computed and the remainder (if any) is thrown away. In the second case, an integer is returned. (3)</p></td> </tr> <tr>
<td><p><code>t1 = t2 % t3</code></p></td> <td><p>The remainder is computed as a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object. (3)</p></td> </tr> <tr>
<td><p><code>q, r = divmod(t1, t2)</code></p></td> <td><p>Computes the quotient and the remainder: <code>q = t1 // t2</code> (3) and <code>r = t1 % t2</code>. q is an integer and r is a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object.</p></td> </tr> <tr>
<td><p><code>+t1</code></p></td> <td><p>Returns a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object with the same value. (2)</p></td> </tr> <tr>
<td><p><code>-t1</code></p></td> <td><p>equivalent to <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a>(-<em>t1.days</em>, -<em>t1.seconds</em>, -<em>t1.microseconds</em>), and to <em>t1</em>* -1. (1)(4)</p></td> </tr> <tr>
<td><p><code>abs(t)</code></p></td> <td><p>equivalent to +<em>t</em> when <code>t.days &gt;= 0</code>, and to -<em>t</em> when <code>t.days &lt; 0</code>. (2)</p></td> </tr> <tr>
<td><p><code>str(t)</code></p></td> <td><p>Returns a string in the form <code>[D day[s], ][H]H:MM:SS[.UUUUUU]</code>, where D is negative for negative <code>t</code>. (5)</p></td> </tr> <tr>
<td><p><code>repr(t)</code></p></td> <td><p>Returns a string representation of the <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object as a constructor call with canonical attribute values.</p></td> </tr>  </table> <p>Notes:</p> <ol class="arabic"> <li>This is exact but may overflow.</li> <li>This is exact and cannot overflow.</li> <li>Division by 0 raises <a class="reference internal" href="exceptions#ZeroDivisionError" title="ZeroDivisionError"><code>ZeroDivisionError</code></a>.</li> <li>-<em>timedelta.max</em> is not representable as a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object.</li> <li>
<p>String representations of <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> objects are normalized similarly to their internal representation. This leads to somewhat unusual results for negative timedeltas. For example:</p> <pre data-language="python">&gt;&gt;&gt; timedelta(hours=-5)
datetime.timedelta(days=-1, seconds=68400)
&gt;&gt;&gt; print(_)
-1 day, 19:00:00
</pre> </li> <li>The expression <code>t2 - t3</code> will always be equal to the expression <code>t2 + (-t3)</code> except when t3 is equal to <code>timedelta.max</code>; in that case the former will produce a result while the latter will overflow.</li> </ol> <p>In addition to the operations listed above, <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> objects support certain additions and subtractions with <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> and <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> objects (see below).</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Floor division and true division of a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object by another <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object are now supported, as are remainder operations and the <a class="reference internal" href="functions#divmod" title="divmod"><code>divmod()</code></a> function. True division and multiplication of a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object by a <a class="reference internal" href="functions#float" title="float"><code>float</code></a> object are now supported.</p> </div> <p>Comparisons of <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> objects are supported, with some caveats.</p> <p>The comparisons <code>==</code> or <code>!=</code> <em>always</em> return a <a class="reference internal" href="functions#bool" title="bool"><code>bool</code></a>, no matter the type of the compared object:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import timedelta
&gt;&gt;&gt; delta1 = timedelta(seconds=57)
&gt;&gt;&gt; delta2 = timedelta(hours=25, seconds=2)
&gt;&gt;&gt; delta2 != delta1
True
&gt;&gt;&gt; delta2 == 5
False
</pre> <p>For all other comparisons (such as <code>&lt;</code> and <code>&gt;</code>), when a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object is compared to an object of a different type, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised:</p> <pre data-language="python">&gt;&gt;&gt; delta2 &gt; delta1
True
&gt;&gt;&gt; delta2 &gt; 5
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: '&gt;' not supported between instances of 'datetime.timedelta' and 'int'
</pre> <p>In Boolean contexts, a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object is considered to be true if and only if it isn’t equal to <code>timedelta(0)</code>.</p> <p>Instance methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="datetime.timedelta.total_seconds">
<code>timedelta.total_seconds()</code> </dt> <dd>
<p>Return the total number of seconds contained in the duration. Equivalent to <code>td / timedelta(seconds=1)</code>. For interval units other than seconds, use the division form directly (e.g. <code>td / timedelta(microseconds=1)</code>).</p> <p>Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <section id="examples-of-usage-timedelta"> <h3>Examples of usage: <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a>
</h3> <p>An additional example of normalization:</p> <pre data-language="python">&gt;&gt;&gt; # Components of another_year add up to exactly 365 days
&gt;&gt;&gt; from datetime import timedelta
&gt;&gt;&gt; year = timedelta(days=365)
&gt;&gt;&gt; another_year = timedelta(weeks=40, days=84, hours=23,
...                          minutes=50, seconds=600)
&gt;&gt;&gt; year == another_year
True
&gt;&gt;&gt; year.total_seconds()
31536000.0
</pre> <p>Examples of <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> arithmetic:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import timedelta
&gt;&gt;&gt; year = timedelta(days=365)
&gt;&gt;&gt; ten_years = 10 * year
&gt;&gt;&gt; ten_years
datetime.timedelta(days=3650)
&gt;&gt;&gt; ten_years.days // 365
10
&gt;&gt;&gt; nine_years = ten_years - year
&gt;&gt;&gt; nine_years
datetime.timedelta(days=3285)
&gt;&gt;&gt; three_years = nine_years // 3
&gt;&gt;&gt; three_years, three_years.days // 365
(datetime.timedelta(days=1095), 3)
</pre> </section> </section> <section id="date-objects"> <span id="datetime-date"></span><h2>date Objects</h2> <p>A <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> object represents a date (year, month and day) in an idealized calendar, the current Gregorian calendar indefinitely extended in both directions.</p> <p>January 1 of year 1 is called day number 1, January 2 of year 1 is called day number 2, and so on. <a class="footnote-reference brackets" href="#id6" id="id2">2</a></p> <dl class="py class"> <dt class="sig sig-object py" id="datetime.date">
<code>class datetime.date(year, month, day)</code> </dt> <dd>
<p>All arguments are required. Arguments must be integers, in the following ranges:</p> <ul class="simple"> <li><code>MINYEAR &lt;= year &lt;= MAXYEAR</code></li> <li><code>1 &lt;= month &lt;= 12</code></li> <li><code>1 &lt;= day &lt;= number of days in the given month and year</code></li> </ul> <p>If an argument outside those ranges is given, <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised.</p> </dd>
</dl> <p>Other constructors, all class methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.today">
<code>classmethod date.today()</code> </dt> <dd>
<p>Return the current local date.</p> <p>This is equivalent to <code>date.fromtimestamp(time.time())</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.fromtimestamp">
<code>classmethod date.fromtimestamp(timestamp)</code> </dt> <dd>
<p>Return the local date corresponding to the POSIX timestamp, such as is returned by <a class="reference internal" href="time#time.time" title="time.time"><code>time.time()</code></a>.</p> <p>This may raise <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a>, if the timestamp is out of the range of values supported by the platform C <code>localtime()</code> function, and <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> on <code>localtime()</code> failure. It’s common for this to be restricted to years from 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by <a class="reference internal" href="#datetime.date.fromtimestamp" title="datetime.date.fromtimestamp"><code>fromtimestamp()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Raise <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a> instead of <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> if the timestamp is out of the range of values supported by the platform C <code>localtime()</code> function. Raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> instead of <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> on <code>localtime()</code> failure.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.fromordinal">
<code>classmethod date.fromordinal(ordinal)</code> </dt> <dd>
<p>Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.</p> <p><a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised unless <code>1 &lt;= ordinal &lt;=
date.max.toordinal()</code>. For any date <em>d</em>, <code>date.fromordinal(d.toordinal()) == d</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.fromisoformat">
<code>classmethod date.fromisoformat(date_string)</code> </dt> <dd>
<p>Return a <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> corresponding to a <em>date_string</em> given in any valid ISO 8601 format, except ordinal dates (e.g. <code>YYYY-DDD</code>):</p> <pre data-language="python">&gt;&gt;&gt; from datetime import date
&gt;&gt;&gt; date.fromisoformat('2019-12-04')
datetime.date(2019, 12, 4)
&gt;&gt;&gt; date.fromisoformat('20191204')
datetime.date(2019, 12, 4)
&gt;&gt;&gt; date.fromisoformat('2021-W01-1')
datetime.date(2021, 1, 4)
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Previously, this method only supported the format <code>YYYY-MM-DD</code>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.fromisocalendar">
<code>classmethod date.fromisocalendar(year, week, day)</code> </dt> <dd>
<p>Return a <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> corresponding to the ISO calendar date specified by year, week and day. This is the inverse of the function <a class="reference internal" href="#datetime.date.isocalendar" title="datetime.date.isocalendar"><code>date.isocalendar()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <p>Class attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.date.min">
<code>date.min</code> </dt> <dd>
<p>The earliest representable date, <code>date(MINYEAR, 1, 1)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.date.max">
<code>date.max</code> </dt> <dd>
<p>The latest representable date, <code>date(MAXYEAR, 12, 31)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.date.resolution">
<code>date.resolution</code> </dt> <dd>
<p>The smallest possible difference between non-equal date objects, <code>timedelta(days=1)</code>.</p> </dd>
</dl> <p>Instance attributes (read-only):</p> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.date.year">
<code>date.year</code> </dt> <dd>
<p>Between <a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code>MINYEAR</code></a> and <a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code>MAXYEAR</code></a> inclusive.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.date.month">
<code>date.month</code> </dt> <dd>
<p>Between 1 and 12 inclusive.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.date.day">
<code>date.day</code> </dt> <dd>
<p>Between 1 and the number of days in the given month of the given year.</p> </dd>
</dl> <p>Supported operations:</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Operation</p></th> <th class="head"><p>Result</p></th> </tr> </thead>  <tr>
<td><p><code>date2 = date1 + timedelta</code></p></td> <td><p><em>date2</em> will be <code>timedelta.days</code> days after <em>date1</em>. (1)</p></td> </tr> <tr>
<td><p><code>date2 = date1 - timedelta</code></p></td> <td><p>Computes <em>date2</em> such that <code>date2 +
timedelta == date1</code>. (2)</p></td> </tr> <tr>
<td><p><code>timedelta = date1 - date2</code></p></td> <td><p>(3)</p></td> </tr> <tr>
<td><p><code>date1 &lt; date2</code></p></td> <td><p><em>date1</em> is considered less than <em>date2</em> when <em>date1</em> precedes <em>date2</em> in time. (4)</p></td> </tr>  </table> <p>Notes:</p> <ol class="arabic simple"> <li>
<em>date2</em> is moved forward in time if <code>timedelta.days &gt; 0</code>, or backward if <code>timedelta.days &lt; 0</code>. Afterward <code>date2 - date1 == timedelta.days</code>. <code>timedelta.seconds</code> and <code>timedelta.microseconds</code> are ignored. <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a> is raised if <code>date2.year</code> would be smaller than <a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code>MINYEAR</code></a> or larger than <a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code>MAXYEAR</code></a>.</li> <li>
<code>timedelta.seconds</code> and <code>timedelta.microseconds</code> are ignored.</li> <li>This is exact, and cannot overflow. timedelta.seconds and timedelta.microseconds are 0, and date2 + timedelta == date1 after.</li> <li>In other words, <code>date1 &lt; date2</code> if and only if <code>date1.toordinal() &lt;
date2.toordinal()</code>. Date comparison raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if the other comparand isn’t also a <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> object. However, <code>NotImplemented</code> is returned instead if the other comparand has a <code>timetuple()</code> attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. If not, when a <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> object is compared to an object of a different type, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised unless the comparison is <code>==</code> or <code>!=</code>. The latter cases return <a class="reference internal" href="constants#False" title="False"><code>False</code></a> or <a class="reference internal" href="constants#True" title="True"><code>True</code></a>, respectively.</li> </ol> <p>In Boolean contexts, all <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> objects are considered to be true.</p> <p>Instance methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.replace">
<code>date.replace(year=self.year, month=self.month, day=self.day)</code> </dt> <dd>
<p>Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified.</p> <p>Example:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import date
&gt;&gt;&gt; d = date(2002, 12, 31)
&gt;&gt;&gt; d.replace(day=26)
datetime.date(2002, 12, 26)
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.timetuple">
<code>date.timetuple()</code> </dt> <dd>
<p>Return a <a class="reference internal" href="time#time.struct_time" title="time.struct_time"><code>time.struct_time</code></a> such as returned by <a class="reference internal" href="time#time.localtime" title="time.localtime"><code>time.localtime()</code></a>.</p> <p>The hours, minutes and seconds are 0, and the DST flag is -1.</p> <p><code>d.timetuple()</code> is equivalent to:</p> <pre data-language="python">time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))
</pre> <p>where <code>yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1</code> is the day number within the current year starting with <code>1</code> for January 1st.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.toordinal">
<code>date.toordinal()</code> </dt> <dd>
<p>Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> object <em>d</em>, <code>date.fromordinal(d.toordinal()) == d</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.weekday">
<code>date.weekday()</code> </dt> <dd>
<p>Return the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, <code>date(2002, 12, 4).weekday() == 2</code>, a Wednesday. See also <a class="reference internal" href="#datetime.date.isoweekday" title="datetime.date.isoweekday"><code>isoweekday()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.isoweekday">
<code>date.isoweekday()</code> </dt> <dd>
<p>Return the day of the week as an integer, where Monday is 1 and Sunday is 7. For example, <code>date(2002, 12, 4).isoweekday() == 3</code>, a Wednesday. See also <a class="reference internal" href="#datetime.date.weekday" title="datetime.date.weekday"><code>weekday()</code></a>, <a class="reference internal" href="#datetime.date.isocalendar" title="datetime.date.isocalendar"><code>isocalendar()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.isocalendar">
<code>date.isocalendar()</code> </dt> <dd>
<p>Return a <a class="reference internal" href="../glossary#term-named-tuple"><span class="xref std std-term">named tuple</span></a> object with three components: <code>year</code>, <code>week</code> and <code>weekday</code>.</p> <p>The ISO calendar is a widely used variant of the Gregorian calendar. <a class="footnote-reference brackets" href="#id7" id="id3">3</a></p> <p>The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.</p> <p>For example, 2004 begins on a Thursday, so the first week of ISO year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import date
&gt;&gt;&gt; date(2003, 12, 29).isocalendar()
datetime.IsoCalendarDate(year=2004, week=1, weekday=1)
&gt;&gt;&gt; date(2004, 1, 4).isocalendar()
datetime.IsoCalendarDate(year=2004, week=1, weekday=7)
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Result changed from a tuple to a <a class="reference internal" href="../glossary#term-named-tuple"><span class="xref std std-term">named tuple</span></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.isoformat">
<code>date.isoformat()</code> </dt> <dd>
<p>Return a string representing the date in ISO 8601 format, <code>YYYY-MM-DD</code>:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import date
&gt;&gt;&gt; date(2002, 12, 4).isoformat()
'2002-12-04'
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.__str__">
<code>date.__str__()</code> </dt> <dd>
<p>For a date <em>d</em>, <code>str(d)</code> is equivalent to <code>d.isoformat()</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.ctime">
<code>date.ctime()</code> </dt> <dd>
<p>Return a string representing the date:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import date
&gt;&gt;&gt; date(2002, 12, 4).ctime()
'Wed Dec  4 00:00:00 2002'
</pre> <p><code>d.ctime()</code> is equivalent to:</p> <pre data-language="python">time.ctime(time.mktime(d.timetuple()))
</pre> <p>on platforms where the native C <code>ctime()</code> function (which <a class="reference internal" href="time#time.ctime" title="time.ctime"><code>time.ctime()</code></a> invokes, but which <a class="reference internal" href="#datetime.date.ctime" title="datetime.date.ctime"><code>date.ctime()</code></a> does not invoke) conforms to the C standard.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.strftime">
<code>date.strftime(format)</code> </dt> <dd>
<p>Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. See also <a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a> and <a class="reference internal" href="#datetime.date.isoformat" title="datetime.date.isoformat"><code>date.isoformat()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.date.__format__">
<code>date.__format__(format)</code> </dt> <dd>
<p>Same as <a class="reference internal" href="#datetime.date.strftime" title="datetime.date.strftime"><code>date.strftime()</code></a>. This makes it possible to specify a format string for a <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> object in <a class="reference internal" href="../reference/lexical_analysis#f-strings"><span class="std std-ref">formatted string literals</span></a> and when using <a class="reference internal" href="stdtypes#str.format" title="str.format"><code>str.format()</code></a>. See also <a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a> and <a class="reference internal" href="#datetime.date.isoformat" title="datetime.date.isoformat"><code>date.isoformat()</code></a>.</p> </dd>
</dl> <section id="examples-of-usage-date"> <h3>Examples of Usage: <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a>
</h3> <p>Example of counting days to an event:</p> <pre data-language="python">&gt;&gt;&gt; import time
&gt;&gt;&gt; from datetime import date
&gt;&gt;&gt; today = date.today()
&gt;&gt;&gt; today
datetime.date(2007, 12, 5)
&gt;&gt;&gt; today == date.fromtimestamp(time.time())
True
&gt;&gt;&gt; my_birthday = date(today.year, 6, 24)
&gt;&gt;&gt; if my_birthday &lt; today:
...     my_birthday = my_birthday.replace(year=today.year + 1)
...
&gt;&gt;&gt; my_birthday
datetime.date(2008, 6, 24)
&gt;&gt;&gt; time_to_birthday = abs(my_birthday - today)
&gt;&gt;&gt; time_to_birthday.days
202
</pre> <p>More examples of working with <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a>:</p> <pre data-language="pycon3">&gt;&gt;&gt; from datetime import date
&gt;&gt;&gt; d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
&gt;&gt;&gt; d
datetime.date(2002, 3, 11)

&gt;&gt;&gt; # Methods related to formatting string output
&gt;&gt;&gt; d.isoformat()
'2002-03-11'
&gt;&gt;&gt; d.strftime("%d/%m/%y")
'11/03/02'
&gt;&gt;&gt; d.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
&gt;&gt;&gt; d.ctime()
'Mon Mar 11 00:00:00 2002'
&gt;&gt;&gt; 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
'The day is 11, the month is March.'

&gt;&gt;&gt; # Methods for to extracting 'components' under different calendars
&gt;&gt;&gt; t = d.timetuple()
&gt;&gt;&gt; for i in t:     
...     print(i)
2002                # year
3                   # month
11                  # day
0
0
0
0                   # weekday (0 = Monday)
70                  # 70th day in the year
-1
&gt;&gt;&gt; ic = d.isocalendar()
&gt;&gt;&gt; for i in ic:    
...     print(i)
2002                # ISO year
11                  # ISO week number
1                   # ISO day number ( 1 = Monday )

&gt;&gt;&gt; # A date object is immutable; all operations produce a new object
&gt;&gt;&gt; d.replace(year=2005)
datetime.date(2005, 3, 11)
</pre> </section> </section> <section id="datetime-objects"> <span id="datetime-datetime"></span><h2>datetime Objects</h2> <p>A <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object is a single object containing all the information from a <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> object and a <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object.</p> <p>Like a <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> object, <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> assumes the current Gregorian calendar extended in both directions; like a <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object, <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> assumes there are exactly 3600*24 seconds in every day.</p> <p>Constructor:</p> <dl class="py class"> <dt class="sig sig-object py" id="datetime.datetime">
<code>class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)</code> </dt> <dd>
<p>The <em>year</em>, <em>month</em> and <em>day</em> arguments are required. <em>tzinfo</em> may be <code>None</code>, or an instance of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass. The remaining arguments must be integers in the following ranges:</p> <ul class="simple"> <li>
<code>MINYEAR &lt;= year &lt;= MAXYEAR</code>,</li> <li>
<code>1 &lt;= month &lt;= 12</code>,</li> <li>
<code>1 &lt;= day &lt;= number of days in the given month and year</code>,</li> <li>
<code>0 &lt;= hour &lt; 24</code>,</li> <li>
<code>0 &lt;= minute &lt; 60</code>,</li> <li>
<code>0 &lt;= second &lt; 60</code>,</li> <li>
<code>0 &lt;= microsecond &lt; 1000000</code>,</li> <li>
<code>fold in [0, 1]</code>.</li> </ul> <p>If an argument outside those ranges is given, <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6: </span>Added the <code>fold</code> argument.</p> </div> </dd>
</dl> <p>Other constructors, all class methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.today">
<code>classmethod datetime.today()</code> </dt> <dd>
<p>Return the current local datetime, with <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> <code>None</code>.</p> <p>Equivalent to:</p> <pre data-language="python">datetime.fromtimestamp(time.time())
</pre> <p>See also <a class="reference internal" href="#datetime.datetime.now" title="datetime.datetime.now"><code>now()</code></a>, <a class="reference internal" href="#datetime.datetime.fromtimestamp" title="datetime.datetime.fromtimestamp"><code>fromtimestamp()</code></a>.</p> <p>This method is functionally equivalent to <a class="reference internal" href="#datetime.datetime.now" title="datetime.datetime.now"><code>now()</code></a>, but without a <code>tz</code> parameter.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.now">
<code>classmethod datetime.now(tz=None)</code> </dt> <dd>
<p>Return the current local date and time.</p> <p>If optional argument <em>tz</em> is <code>None</code> or not specified, this is like <a class="reference internal" href="#datetime.datetime.today" title="datetime.datetime.today"><code>today()</code></a>, but, if possible, supplies more precision than can be gotten from going through a <a class="reference internal" href="time#time.time" title="time.time"><code>time.time()</code></a> timestamp (for example, this may be possible on platforms supplying the C <code>gettimeofday()</code> function).</p> <p>If <em>tz</em> is not <code>None</code>, it must be an instance of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass, and the current date and time are converted to <em>tz</em>’s time zone.</p> <p>This function is preferred over <a class="reference internal" href="#datetime.datetime.today" title="datetime.datetime.today"><code>today()</code></a> and <a class="reference internal" href="#datetime.datetime.utcnow" title="datetime.datetime.utcnow"><code>utcnow()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.utcnow">
<code>classmethod datetime.utcnow()</code> </dt> <dd>
<p>Return the current UTC date and time, with <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> <code>None</code>.</p> <p>This is like <a class="reference internal" href="#datetime.datetime.now" title="datetime.datetime.now"><code>now()</code></a>, but returns the current UTC date and time, as a naive <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object. An aware current UTC datetime can be obtained by calling <code>datetime.now(timezone.utc)</code>. See also <a class="reference internal" href="#datetime.datetime.now" title="datetime.datetime.now"><code>now()</code></a>.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Because naive <code>datetime</code> objects are treated by many <code>datetime</code> methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling <code>datetime.now(timezone.utc)</code>.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.12: </span>Use <a class="reference internal" href="#datetime.datetime.now" title="datetime.datetime.now"><code>datetime.now()</code></a> with <a class="reference internal" href="#datetime.UTC" title="datetime.UTC"><code>UTC</code></a> instead.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.fromtimestamp">
<code>classmethod datetime.fromtimestamp(timestamp, tz=None)</code> </dt> <dd>
<p>Return the local date and time corresponding to the POSIX timestamp, such as is returned by <a class="reference internal" href="time#time.time" title="time.time"><code>time.time()</code></a>. If optional argument <em>tz</em> is <code>None</code> or not specified, the timestamp is converted to the platform’s local date and time, and the returned <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object is naive.</p> <p>If <em>tz</em> is not <code>None</code>, it must be an instance of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass, and the timestamp is converted to <em>tz</em>’s time zone.</p> <p><a class="reference internal" href="#datetime.datetime.fromtimestamp" title="datetime.datetime.fromtimestamp"><code>fromtimestamp()</code></a> may raise <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a>, if the timestamp is out of the range of values supported by the platform C <code>localtime()</code> or <code>gmtime()</code> functions, and <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> on <code>localtime()</code> or <code>gmtime()</code> failure. It’s common for this to be restricted to years in 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by <a class="reference internal" href="#datetime.datetime.fromtimestamp" title="datetime.datetime.fromtimestamp"><code>fromtimestamp()</code></a>, and then it’s possible to have two timestamps differing by a second that yield identical <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> objects. This method is preferred over <a class="reference internal" href="#datetime.datetime.utcfromtimestamp" title="datetime.datetime.utcfromtimestamp"><code>utcfromtimestamp()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Raise <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a> instead of <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> if the timestamp is out of the range of values supported by the platform C <code>localtime()</code> or <code>gmtime()</code> functions. Raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> instead of <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> on <code>localtime()</code> or <code>gmtime()</code> failure.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><a class="reference internal" href="#datetime.datetime.fromtimestamp" title="datetime.datetime.fromtimestamp"><code>fromtimestamp()</code></a> may return instances with <a class="reference internal" href="#datetime.datetime.fold" title="datetime.datetime.fold"><code>fold</code></a> set to 1.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.utcfromtimestamp">
<code>classmethod datetime.utcfromtimestamp(timestamp)</code> </dt> <dd>
<p>Return the UTC <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> corresponding to the POSIX timestamp, with <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> <code>None</code>. (The resulting object is naive.)</p> <p>This may raise <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a>, if the timestamp is out of the range of values supported by the platform C <code>gmtime()</code> function, and <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> on <code>gmtime()</code> failure. It’s common for this to be restricted to years in 1970 through 2038.</p> <p>To get an aware <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object, call <a class="reference internal" href="#datetime.datetime.fromtimestamp" title="datetime.datetime.fromtimestamp"><code>fromtimestamp()</code></a>:</p> <pre data-language="python">datetime.fromtimestamp(timestamp, timezone.utc)
</pre> <p>On the POSIX compliant platforms, it is equivalent to the following expression:</p> <pre data-language="python">datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
</pre> <p>except the latter formula always supports the full years range: between <a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code>MINYEAR</code></a> and <a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code>MAXYEAR</code></a> inclusive.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Because naive <code>datetime</code> objects are treated by many <code>datetime</code> methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing a specific timestamp in UTC is by calling <code>datetime.fromtimestamp(timestamp, tz=timezone.utc)</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Raise <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a> instead of <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> if the timestamp is out of the range of values supported by the platform C <code>gmtime()</code> function. Raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> instead of <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> on <code>gmtime()</code> failure.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.12: </span>Use <a class="reference internal" href="#datetime.datetime.fromtimestamp" title="datetime.datetime.fromtimestamp"><code>datetime.fromtimestamp()</code></a> with <a class="reference internal" href="#datetime.UTC" title="datetime.UTC"><code>UTC</code></a> instead.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.fromordinal">
<code>classmethod datetime.fromordinal(ordinal)</code> </dt> <dd>
<p>Return the <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised unless <code>1
&lt;= ordinal &lt;= datetime.max.toordinal()</code>. The hour, minute, second and microsecond of the result are all 0, and <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> is <code>None</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.combine">
<code>classmethod datetime.combine(date, time, tzinfo=time.tzinfo)</code> </dt> <dd>
<p>Return a new <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object whose date components are equal to the given <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> object’s, and whose time components are equal to the given <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object’s. If the <em>tzinfo</em> argument is provided, its value is used to set the <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attribute of the result, otherwise the <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code>tzinfo</code></a> attribute of the <em>time</em> argument is used. If the <em>date</em> argument is a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object, its time components and <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attributes are ignored.</p> <p>For any <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object <em>d</em>, <code>d == datetime.combine(d.date(), d.time(), d.tzinfo)</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Added the <em>tzinfo</em> argument.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.fromisoformat">
<code>classmethod datetime.fromisoformat(date_string)</code> </dt> <dd>
<p>Return a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> corresponding to a <em>date_string</em> in any valid ISO 8601 format, with the following exceptions:</p> <ol class="arabic simple"> <li>Time zone offsets may have fractional seconds.</li> <li>The <code>T</code> separator may be replaced by any single unicode character.</li> <li>Ordinal dates are not currently supported.</li> <li>Fractional hours and minutes are not supported.</li> </ol> <p>Examples:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import datetime
&gt;&gt;&gt; datetime.fromisoformat('2011-11-04')
datetime.datetime(2011, 11, 4, 0, 0)
&gt;&gt;&gt; datetime.fromisoformat('20111104')
datetime.datetime(2011, 11, 4, 0, 0)
&gt;&gt;&gt; datetime.fromisoformat('2011-11-04T00:05:23')
datetime.datetime(2011, 11, 4, 0, 5, 23)
&gt;&gt;&gt; datetime.fromisoformat('2011-11-04T00:05:23Z')
datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)
&gt;&gt;&gt; datetime.fromisoformat('20111104T000523')
datetime.datetime(2011, 11, 4, 0, 5, 23)
&gt;&gt;&gt; datetime.fromisoformat('2011-W01-2T00:05:23.283')
datetime.datetime(2011, 1, 4, 0, 5, 23, 283000)
&gt;&gt;&gt; datetime.fromisoformat('2011-11-04 00:05:23.283')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)
&gt;&gt;&gt; datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)
&gt;&gt;&gt; datetime.fromisoformat('2011-11-04T00:05:23+04:00')   
datetime.datetime(2011, 11, 4, 0, 5, 23,
    tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Previously, this method only supported formats that could be emitted by <a class="reference internal" href="#datetime.date.isoformat" title="datetime.date.isoformat"><code>date.isoformat()</code></a> or <a class="reference internal" href="#datetime.datetime.isoformat" title="datetime.datetime.isoformat"><code>datetime.isoformat()</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.fromisocalendar">
<code>classmethod datetime.fromisocalendar(year, week, day)</code> </dt> <dd>
<p>Return a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> corresponding to the ISO calendar date specified by year, week and day. The non-date components of the datetime are populated with their normal default values. This is the inverse of the function <a class="reference internal" href="#datetime.datetime.isocalendar" title="datetime.datetime.isocalendar"><code>datetime.isocalendar()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.strptime">
<code>classmethod datetime.strptime(date_string, format)</code> </dt> <dd>
<p>Return a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> corresponding to <em>date_string</em>, parsed according to <em>format</em>.</p> <p>If <em>format</em> does not contain microseconds or timezone information, this is equivalent to:</p> <pre data-language="python">datetime(*(time.strptime(date_string, format)[0:6]))
</pre> <p><a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised if the date_string and format can’t be parsed by <a class="reference internal" href="time#time.strptime" title="time.strptime"><code>time.strptime()</code></a> or if it returns a value which isn’t a time tuple. See also <a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a> and <a class="reference internal" href="#datetime.datetime.fromisoformat" title="datetime.datetime.fromisoformat"><code>datetime.fromisoformat()</code></a>.</p> </dd>
</dl> <p>Class attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.min">
<code>datetime.min</code> </dt> <dd>
<p>The earliest representable <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a>, <code>datetime(MINYEAR, 1, 1,
tzinfo=None)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.max">
<code>datetime.max</code> </dt> <dd>
<p>The latest representable <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a>, <code>datetime(MAXYEAR, 12, 31, 23, 59,
59, 999999, tzinfo=None)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.resolution">
<code>datetime.resolution</code> </dt> <dd>
<p>The smallest possible difference between non-equal <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> objects, <code>timedelta(microseconds=1)</code>.</p> </dd>
</dl> <p>Instance attributes (read-only):</p> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.year">
<code>datetime.year</code> </dt> <dd>
<p>Between <a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code>MINYEAR</code></a> and <a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code>MAXYEAR</code></a> inclusive.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.month">
<code>datetime.month</code> </dt> <dd>
<p>Between 1 and 12 inclusive.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.day">
<code>datetime.day</code> </dt> <dd>
<p>Between 1 and the number of days in the given month of the given year.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.hour">
<code>datetime.hour</code> </dt> <dd>
<p>In <code>range(24)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.minute">
<code>datetime.minute</code> </dt> <dd>
<p>In <code>range(60)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.second">
<code>datetime.second</code> </dt> <dd>
<p>In <code>range(60)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.microsecond">
<code>datetime.microsecond</code> </dt> <dd>
<p>In <code>range(1000000)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.tzinfo">
<code>datetime.tzinfo</code> </dt> <dd>
<p>The object passed as the <em>tzinfo</em> argument to the <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> constructor, or <code>None</code> if none was passed.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.datetime.fold">
<code>datetime.fold</code> </dt> <dd>
<p>In <code>[0, 1]</code>. Used to disambiguate wall times during a repeated interval. (A repeated interval occurs when clocks are rolled back at the end of daylight saving time or when the UTC offset for the current zone is decreased for political reasons.) The value 0 (1) represents the earlier (later) of the two moments with the same wall time representation.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <p>Supported operations:</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Operation</p></th> <th class="head"><p>Result</p></th> </tr> </thead>  <tr>
<td><p><code>datetime2 = datetime1 + timedelta</code></p></td> <td><p>(1)</p></td> </tr> <tr>
<td><p><code>datetime2 = datetime1 - timedelta</code></p></td> <td><p>(2)</p></td> </tr> <tr>
<td><p><code>timedelta = datetime1 - datetime2</code></p></td> <td><p>(3)</p></td> </tr> <tr>
<td><p><code>datetime1 &lt; datetime2</code></p></td> <td><p>Compares <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> to <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a>. (4)</p></td> </tr>  </table> <ol class="arabic"> <li>datetime2 is a duration of timedelta removed from datetime1, moving forward in time if <code>timedelta.days</code> &gt; 0, or backward if <code>timedelta.days</code> &lt; 0. The result has the same <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attribute as the input datetime, and datetime2 - datetime1 == timedelta after. <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a> is raised if datetime2.year would be smaller than <a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code>MINYEAR</code></a> or larger than <a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code>MAXYEAR</code></a>. Note that no time zone adjustments are done even if the input is an aware object.</li> <li>Computes the datetime2 such that datetime2 + timedelta == datetime1. As for addition, the result has the same <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attribute as the input datetime, and no time zone adjustments are done even if the input is aware.</li> <li>
<p>Subtraction of a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> from a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</p> <p>If both are naive, or both are aware and have the same <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attribute, the <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attributes are ignored, and the result is a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object <em>t</em> such that <code>datetime2 + t == datetime1</code>. No time zone adjustments are done in this case.</p> <p>If both are aware and have different <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attributes, <code>a-b</code> acts as if <em>a</em> and <em>b</em> were first converted to naive UTC datetimes first. The result is <code>(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
- b.utcoffset())</code> except that the implementation never overflows.</p> </li> <li>
<p><em>datetime1</em> is considered less than <em>datetime2</em> when <em>datetime1</em> precedes <em>datetime2</em> in time.</p> <p>If one comparand is naive and the other is aware, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised if an order comparison is attempted. For equality comparisons, naive instances are never equal to aware instances.</p> <p>If both comparands are aware, and have the same <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attribute, the common <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attribute is ignored and the base datetimes are compared. If both comparands are aware and have different <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from <code>self.utcoffset()</code>).</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Equality comparisons between aware and naive <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> instances don’t raise <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>In order to stop comparison from falling back to the default scheme of comparing object addresses, datetime comparison normally raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if the other comparand isn’t also a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object. However, <code>NotImplemented</code> is returned instead if the other comparand has a <code>timetuple()</code> attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. If not, when a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object is compared to an object of a different type, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised unless the comparison is <code>==</code> or <code>!=</code>. The latter cases return <a class="reference internal" href="constants#False" title="False"><code>False</code></a> or <a class="reference internal" href="constants#True" title="True"><code>True</code></a>, respectively.</p> </div> </li> </ol> <p>Instance methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.date">
<code>datetime.date()</code> </dt> <dd>
<p>Return <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> object with same year, month and day.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.time">
<code>datetime.time()</code> </dt> <dd>
<p>Return <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object with same hour, minute, second, microsecond and fold. <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> is <code>None</code>. See also method <a class="reference internal" href="#datetime.datetime.timetz" title="datetime.datetime.timetz"><code>timetz()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The fold value is copied to the returned <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.timetz">
<code>datetime.timetz()</code> </dt> <dd>
<p>Return <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object with same hour, minute, second, microsecond, fold, and tzinfo attributes. See also method <a class="reference internal" href="time#module-time" title="time: Time access and conversions."><code>time()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The fold value is copied to the returned <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.replace">
<code>datetime.replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)</code> </dt> <dd>
<p>Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified. Note that <code>tzinfo=None</code> can be specified to create a naive datetime from an aware datetime with no conversion of date and time data.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6: </span>Added the <code>fold</code> argument.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.astimezone">
<code>datetime.astimezone(tz=None)</code> </dt> <dd>
<p>Return a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object with new <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attribute <em>tz</em>, adjusting the date and time data so the result is the same UTC time as <em>self</em>, but in <em>tz</em>’s local time.</p> <p>If provided, <em>tz</em> must be an instance of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass, and its <a class="reference internal" href="#datetime.datetime.utcoffset" title="datetime.datetime.utcoffset"><code>utcoffset()</code></a> and <a class="reference internal" href="#datetime.datetime.dst" title="datetime.datetime.dst"><code>dst()</code></a> methods must not return <code>None</code>. If <em>self</em> is naive, it is presumed to represent time in the system timezone.</p> <p>If called without arguments (or with <code>tz=None</code>) the system local timezone is assumed for the target timezone. The <code>.tzinfo</code> attribute of the converted datetime instance will be set to an instance of <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a> with the zone name and offset obtained from the OS.</p> <p>If <code>self.tzinfo</code> is <em>tz</em>, <code>self.astimezone(tz)</code> is equal to <em>self</em>: no adjustment of date or time data is performed. Else the result is local time in the timezone <em>tz</em>, representing the same UTC time as <em>self</em>: after <code>astz = dt.astimezone(tz)</code>, <code>astz - astz.utcoffset()</code> will have the same date and time data as <code>dt - dt.utcoffset()</code>.</p> <p>If you merely want to attach a time zone object <em>tz</em> to a datetime <em>dt</em> without adjustment of date and time data, use <code>dt.replace(tzinfo=tz)</code>. If you merely want to remove the time zone object from an aware datetime <em>dt</em> without conversion of date and time data, use <code>dt.replace(tzinfo=None)</code>.</p> <p>Note that the default <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code>tzinfo.fromutc()</code></a> method can be overridden in a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass to affect the result returned by <a class="reference internal" href="#datetime.datetime.astimezone" title="datetime.datetime.astimezone"><code>astimezone()</code></a>. Ignoring error cases, <a class="reference internal" href="#datetime.datetime.astimezone" title="datetime.datetime.astimezone"><code>astimezone()</code></a> acts like:</p> <pre data-language="python">def astimezone(self, tz):
    if self.tzinfo is tz:
        return self
    # Convert self to UTC, and attach the new time zone object.
    utc = (self - self.utcoffset()).replace(tzinfo=tz)
    # Convert from UTC to tz's local time.
    return tz.fromutc(utc)
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span><em>tz</em> now can be omitted.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The <a class="reference internal" href="#datetime.datetime.astimezone" title="datetime.datetime.astimezone"><code>astimezone()</code></a> method can now be called on naive instances that are presumed to represent system local time.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.utcoffset">
<code>datetime.utcoffset()</code> </dt> <dd>
<p>If <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> is <code>None</code>, returns <code>None</code>, else returns <code>self.tzinfo.utcoffset(self)</code>, and raises an exception if the latter doesn’t return <code>None</code> or a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object with magnitude less than one day.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The UTC offset is not restricted to a whole number of minutes.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.dst">
<code>datetime.dst()</code> </dt> <dd>
<p>If <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> is <code>None</code>, returns <code>None</code>, else returns <code>self.tzinfo.dst(self)</code>, and raises an exception if the latter doesn’t return <code>None</code> or a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object with magnitude less than one day.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The DST offset is not restricted to a whole number of minutes.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.tzname">
<code>datetime.tzname()</code> </dt> <dd>
<p>If <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> is <code>None</code>, returns <code>None</code>, else returns <code>self.tzinfo.tzname(self)</code>, raises an exception if the latter doesn’t return <code>None</code> or a string object,</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.timetuple">
<code>datetime.timetuple()</code> </dt> <dd>
<p>Return a <a class="reference internal" href="time#time.struct_time" title="time.struct_time"><code>time.struct_time</code></a> such as returned by <a class="reference internal" href="time#time.localtime" title="time.localtime"><code>time.localtime()</code></a>.</p> <p><code>d.timetuple()</code> is equivalent to:</p> <pre data-language="python">time.struct_time((d.year, d.month, d.day,
                  d.hour, d.minute, d.second,
                  d.weekday(), yday, dst))
</pre> <p>where <code>yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1</code> is the day number within the current year starting with <code>1</code> for January 1st. The <code>tm_isdst</code> flag of the result is set according to the <a class="reference internal" href="#datetime.datetime.dst" title="datetime.datetime.dst"><code>dst()</code></a> method: <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> is <code>None</code> or <a class="reference internal" href="#datetime.datetime.dst" title="datetime.datetime.dst"><code>dst()</code></a> returns <code>None</code>, <code>tm_isdst</code> is set to <code>-1</code>; else if <a class="reference internal" href="#datetime.datetime.dst" title="datetime.datetime.dst"><code>dst()</code></a> returns a non-zero value, <code>tm_isdst</code> is set to <code>1</code>; else <code>tm_isdst</code> is set to <code>0</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.utctimetuple">
<code>datetime.utctimetuple()</code> </dt> <dd>
<p>If <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> instance <em>d</em> is naive, this is the same as <code>d.timetuple()</code> except that <code>tm_isdst</code> is forced to 0 regardless of what <code>d.dst()</code> returns. DST is never in effect for a UTC time.</p> <p>If <em>d</em> is aware, <em>d</em> is normalized to UTC time, by subtracting <code>d.utcoffset()</code>, and a <a class="reference internal" href="time#time.struct_time" title="time.struct_time"><code>time.struct_time</code></a> for the normalized time is returned. <code>tm_isdst</code> is forced to 0. Note that an <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a> may be raised if <em>d</em>.year was <code>MINYEAR</code> or <code>MAXYEAR</code> and UTC adjustment spills over a year boundary.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Because naive <code>datetime</code> objects are treated by many <code>datetime</code> methods as local times, it is preferred to use aware datetimes to represent times in UTC; as a result, using <a class="reference internal" href="#datetime.datetime.utctimetuple" title="datetime.datetime.utctimetuple"><code>datetime.utctimetuple()</code></a> may give misleading results. If you have a naive <code>datetime</code> representing UTC, use <code>datetime.replace(tzinfo=timezone.utc)</code> to make it aware, at which point you can use <a class="reference internal" href="#datetime.datetime.timetuple" title="datetime.datetime.timetuple"><code>datetime.timetuple()</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.toordinal">
<code>datetime.toordinal()</code> </dt> <dd>
<p>Return the proleptic Gregorian ordinal of the date. The same as <code>self.date().toordinal()</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.timestamp">
<code>datetime.timestamp()</code> </dt> <dd>
<p>Return POSIX timestamp corresponding to the <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> instance. The return value is a <a class="reference internal" href="functions#float" title="float"><code>float</code></a> similar to that returned by <a class="reference internal" href="time#time.time" title="time.time"><code>time.time()</code></a>.</p> <p>Naive <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> instances are assumed to represent local time and this method relies on the platform C <code>mktime()</code> function to perform the conversion. Since <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> supports wider range of values than <code>mktime()</code> on many platforms, this method may raise <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a> or <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> for times far in the past or far in the future.</p> <p>For aware <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> instances, the return value is computed as:</p> <pre data-language="python">(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The <a class="reference internal" href="#datetime.datetime.timestamp" title="datetime.datetime.timestamp"><code>timestamp()</code></a> method uses the <a class="reference internal" href="#datetime.datetime.fold" title="datetime.datetime.fold"><code>fold</code></a> attribute to disambiguate the times during a repeated interval.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>There is no method to obtain the POSIX timestamp directly from a naive <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying <code>tzinfo=timezone.utc</code>:</p> <pre data-language="python">timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
</pre> <p>or by calculating the timestamp directly:</p> <pre data-language="python">timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
</pre> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.weekday">
<code>datetime.weekday()</code> </dt> <dd>
<p>Return the day of the week as an integer, where Monday is 0 and Sunday is 6. The same as <code>self.date().weekday()</code>. See also <a class="reference internal" href="#datetime.datetime.isoweekday" title="datetime.datetime.isoweekday"><code>isoweekday()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.isoweekday">
<code>datetime.isoweekday()</code> </dt> <dd>
<p>Return the day of the week as an integer, where Monday is 1 and Sunday is 7. The same as <code>self.date().isoweekday()</code>. See also <a class="reference internal" href="#datetime.datetime.weekday" title="datetime.datetime.weekday"><code>weekday()</code></a>, <a class="reference internal" href="#datetime.datetime.isocalendar" title="datetime.datetime.isocalendar"><code>isocalendar()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.isocalendar">
<code>datetime.isocalendar()</code> </dt> <dd>
<p>Return a <a class="reference internal" href="../glossary#term-named-tuple"><span class="xref std std-term">named tuple</span></a> with three components: <code>year</code>, <code>week</code> and <code>weekday</code>. The same as <code>self.date().isocalendar()</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.isoformat">
<code>datetime.isoformat(sep='T', timespec='auto')</code> </dt> <dd>
<p>Return a string representing the date and time in ISO 8601 format:</p> <ul class="simple"> <li>
<code>YYYY-MM-DDTHH:MM:SS.ffffff</code>, if <a class="reference internal" href="#datetime.datetime.microsecond" title="datetime.datetime.microsecond"><code>microsecond</code></a> is not 0</li> <li>
<code>YYYY-MM-DDTHH:MM:SS</code>, if <a class="reference internal" href="#datetime.datetime.microsecond" title="datetime.datetime.microsecond"><code>microsecond</code></a> is 0</li> </ul> <p>If <a class="reference internal" href="#datetime.datetime.utcoffset" title="datetime.datetime.utcoffset"><code>utcoffset()</code></a> does not return <code>None</code>, a string is appended, giving the UTC offset:</p> <ul class="simple"> <li>
<code>YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]</code>, if <a class="reference internal" href="#datetime.datetime.microsecond" title="datetime.datetime.microsecond"><code>microsecond</code></a> is not 0</li> <li>
<code>YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]</code>, if <a class="reference internal" href="#datetime.datetime.microsecond" title="datetime.datetime.microsecond"><code>microsecond</code></a> is 0</li> </ul> <p>Examples:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import datetime, timezone
&gt;&gt;&gt; datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()
'2019-05-18T15:17:08.132263'
&gt;&gt;&gt; datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()
'2019-05-18T15:17:00+00:00'
</pre> <p>The optional argument <em>sep</em> (default <code>'T'</code>) is a one-character separator, placed between the date and time portions of the result. For example:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import tzinfo, timedelta, datetime
&gt;&gt;&gt; class TZ(tzinfo):
...     """A time zone with an arbitrary, constant -06:39 offset."""
...     def utcoffset(self, dt):
...         return timedelta(hours=-6, minutes=-39)
...
&gt;&gt;&gt; datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
&gt;&gt;&gt; datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()
'2009-11-27T00:00:00.000100-06:39'
</pre> <p>The optional argument <em>timespec</em> specifies the number of additional components of the time to include (the default is <code>'auto'</code>). It can be one of the following:</p> <ul class="simple"> <li>
<code>'auto'</code>: Same as <code>'seconds'</code> if <a class="reference internal" href="#datetime.datetime.microsecond" title="datetime.datetime.microsecond"><code>microsecond</code></a> is 0, same as <code>'microseconds'</code> otherwise.</li> <li>
<code>'hours'</code>: Include the <a class="reference internal" href="#datetime.datetime.hour" title="datetime.datetime.hour"><code>hour</code></a> in the two-digit <code>HH</code> format.</li> <li>
<code>'minutes'</code>: Include <a class="reference internal" href="#datetime.datetime.hour" title="datetime.datetime.hour"><code>hour</code></a> and <a class="reference internal" href="#datetime.datetime.minute" title="datetime.datetime.minute"><code>minute</code></a> in <code>HH:MM</code> format.</li> <li>
<code>'seconds'</code>: Include <a class="reference internal" href="#datetime.datetime.hour" title="datetime.datetime.hour"><code>hour</code></a>, <a class="reference internal" href="#datetime.datetime.minute" title="datetime.datetime.minute"><code>minute</code></a>, and <a class="reference internal" href="#datetime.datetime.second" title="datetime.datetime.second"><code>second</code></a> in <code>HH:MM:SS</code> format.</li> <li>
<code>'milliseconds'</code>: Include full time, but truncate fractional second part to milliseconds. <code>HH:MM:SS.sss</code> format.</li> <li>
<code>'microseconds'</code>: Include full time in <code>HH:MM:SS.ffffff</code> format.</li> </ul> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Excluded time components are truncated, not rounded.</p> </div> <p><a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> will be raised on an invalid <em>timespec</em> argument:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import datetime
&gt;&gt;&gt; datetime.now().isoformat(timespec='minutes')   
'2002-12-25T00:00'
&gt;&gt;&gt; dt = datetime(2015, 1, 1, 12, 30, 59, 0)
&gt;&gt;&gt; dt.isoformat(timespec='microseconds')
'2015-01-01T12:30:59.000000'
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6: </span>Added the <em>timespec</em> argument.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.__str__">
<code>datetime.__str__()</code> </dt> <dd>
<p>For a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> instance <em>d</em>, <code>str(d)</code> is equivalent to <code>d.isoformat(' ')</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.ctime">
<code>datetime.ctime()</code> </dt> <dd>
<p>Return a string representing the date and time:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import datetime
&gt;&gt;&gt; datetime(2002, 12, 4, 20, 30, 40).ctime()
'Wed Dec  4 20:30:40 2002'
</pre> <p>The output string will <em>not</em> include time zone information, regardless of whether the input is aware or naive.</p> <p><code>d.ctime()</code> is equivalent to:</p> <pre data-language="python">time.ctime(time.mktime(d.timetuple()))
</pre> <p>on platforms where the native C <code>ctime()</code> function (which <a class="reference internal" href="time#time.ctime" title="time.ctime"><code>time.ctime()</code></a> invokes, but which <a class="reference internal" href="#datetime.datetime.ctime" title="datetime.datetime.ctime"><code>datetime.ctime()</code></a> does not invoke) conforms to the C standard.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.strftime">
<code>datetime.strftime(format)</code> </dt> <dd>
<p>Return a string representing the date and time, controlled by an explicit format string. See also <a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a> and <a class="reference internal" href="#datetime.datetime.isoformat" title="datetime.datetime.isoformat"><code>datetime.isoformat()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.datetime.__format__">
<code>datetime.__format__(format)</code> </dt> <dd>
<p>Same as <a class="reference internal" href="#datetime.datetime.strftime" title="datetime.datetime.strftime"><code>datetime.strftime()</code></a>. This makes it possible to specify a format string for a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object in <a class="reference internal" href="../reference/lexical_analysis#f-strings"><span class="std std-ref">formatted string literals</span></a> and when using <a class="reference internal" href="stdtypes#str.format" title="str.format"><code>str.format()</code></a>. See also <a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a> and <a class="reference internal" href="#datetime.datetime.isoformat" title="datetime.datetime.isoformat"><code>datetime.isoformat()</code></a>.</p> </dd>
</dl> <section id="examples-of-usage-datetime"> <h3>Examples of Usage: <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a>
</h3> <p>Examples of working with <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> objects:</p> <pre data-language="pycon3">&gt;&gt;&gt; from datetime import datetime, date, time, timezone

&gt;&gt;&gt; # Using datetime.combine()
&gt;&gt;&gt; d = date(2005, 7, 14)
&gt;&gt;&gt; t = time(12, 30)
&gt;&gt;&gt; datetime.combine(d, t)
datetime.datetime(2005, 7, 14, 12, 30)

&gt;&gt;&gt; # Using datetime.now()
&gt;&gt;&gt; datetime.now()   
datetime.datetime(2007, 12, 6, 16, 29, 43, 79043)   # GMT +1
&gt;&gt;&gt; datetime.now(timezone.utc)   
datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc)

&gt;&gt;&gt; # Using datetime.strptime()
&gt;&gt;&gt; dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
&gt;&gt;&gt; dt
datetime.datetime(2006, 11, 21, 16, 30)

&gt;&gt;&gt; # Using datetime.timetuple() to get tuple of all attributes
&gt;&gt;&gt; tt = dt.timetuple()
&gt;&gt;&gt; for it in tt:   
...     print(it)
...
2006    # year
11      # month
21      # day
16      # hour
30      # minute
0       # second
1       # weekday (0 = Monday)
325     # number of days since 1st January
-1      # dst - method tzinfo.dst() returned None

&gt;&gt;&gt; # Date in ISO format
&gt;&gt;&gt; ic = dt.isocalendar()
&gt;&gt;&gt; for it in ic:   
...     print(it)
...
2006    # ISO year
47      # ISO week
2       # ISO weekday

&gt;&gt;&gt; # Formatting a datetime
&gt;&gt;&gt; dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'
&gt;&gt;&gt; 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
'The day is 21, the month is November, the time is 04:30PM.'
</pre> <p>The example below defines a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass capturing time zone information for Kabul, Afghanistan, which used +4 UTC until 1945 and then +4:30 UTC thereafter:</p> <pre data-language="python">from datetime import timedelta, datetime, tzinfo, timezone

class KabulTz(tzinfo):
    # Kabul used +4 until 1945, when they moved to +4:30
    UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)

    def utcoffset(self, dt):
        if dt.year &lt; 1945:
            return timedelta(hours=4)
        elif (1945, 1, 1, 0, 0) &lt;= dt.timetuple()[:5] &lt; (1945, 1, 1, 0, 30):
            # An ambiguous ("imaginary") half-hour range representing
            # a 'fold' in time due to the shift from +4 to +4:30.
            # If dt falls in the imaginary range, use fold to decide how
            # to resolve. See PEP495.
            return timedelta(hours=4, minutes=(30 if dt.fold else 0))
        else:
            return timedelta(hours=4, minutes=30)

    def fromutc(self, dt):
        # Follow same validations as in datetime.tzinfo
        if not isinstance(dt, datetime):
            raise TypeError("fromutc() requires a datetime argument")
        if dt.tzinfo is not self:
            raise ValueError("dt.tzinfo is not self")

        # A custom implementation is required for fromutc as
        # the input to this function is a datetime with utc values
        # but with a tzinfo set to self.
        # See datetime.astimezone or fromtimestamp.
        if dt.replace(tzinfo=timezone.utc) &gt;= self.UTC_MOVE_DATE:
            return dt + timedelta(hours=4, minutes=30)
        else:
            return dt + timedelta(hours=4)

    def dst(self, dt):
        # Kabul does not observe daylight saving time.
        return timedelta(0)

    def tzname(self, dt):
        if dt &gt;= self.UTC_MOVE_DATE:
            return "+04:30"
        return "+04"
</pre> <p>Usage of <code>KabulTz</code> from above:</p> <pre data-language="python">&gt;&gt;&gt; tz1 = KabulTz()

&gt;&gt;&gt; # Datetime before the change
&gt;&gt;&gt; dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)
&gt;&gt;&gt; print(dt1.utcoffset())
4:00:00

&gt;&gt;&gt; # Datetime after the change
&gt;&gt;&gt; dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)
&gt;&gt;&gt; print(dt2.utcoffset())
4:30:00

&gt;&gt;&gt; # Convert datetime to another time zone
&gt;&gt;&gt; dt3 = dt2.astimezone(timezone.utc)
&gt;&gt;&gt; dt3
datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)
&gt;&gt;&gt; dt2
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())
&gt;&gt;&gt; dt2 == dt3
True
</pre> </section> </section> <section id="time-objects"> <span id="datetime-time"></span><h2>time Objects</h2> <p>A <a class="reference internal" href="time#module-time" title="time: Time access and conversions."><code>time</code></a> object represents a (local) time of day, independent of any particular day, and subject to adjustment via a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> object.</p> <dl class="py class"> <dt class="sig sig-object py" id="datetime.time">
<code>class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)</code> </dt> <dd>
<p>All arguments are optional. <em>tzinfo</em> may be <code>None</code>, or an instance of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass. The remaining arguments must be integers in the following ranges:</p> <ul class="simple"> <li>
<code>0 &lt;= hour &lt; 24</code>,</li> <li>
<code>0 &lt;= minute &lt; 60</code>,</li> <li>
<code>0 &lt;= second &lt; 60</code>,</li> <li>
<code>0 &lt;= microsecond &lt; 1000000</code>,</li> <li>
<code>fold in [0, 1]</code>.</li> </ul> <p>If an argument outside those ranges is given, <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised. All default to <code>0</code> except <em>tzinfo</em>, which defaults to <a class="reference internal" href="constants#None" title="None"><code>None</code></a>.</p> </dd>
</dl> <p>Class attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.time.min">
<code>time.min</code> </dt> <dd>
<p>The earliest representable <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a>, <code>time(0, 0, 0, 0)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.time.max">
<code>time.max</code> </dt> <dd>
<p>The latest representable <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a>, <code>time(23, 59, 59, 999999)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.time.resolution">
<code>time.resolution</code> </dt> <dd>
<p>The smallest possible difference between non-equal <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> objects, <code>timedelta(microseconds=1)</code>, although note that arithmetic on <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> objects is not supported.</p> </dd>
</dl> <p>Instance attributes (read-only):</p> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.time.hour">
<code>time.hour</code> </dt> <dd>
<p>In <code>range(24)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.time.minute">
<code>time.minute</code> </dt> <dd>
<p>In <code>range(60)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.time.second">
<code>time.second</code> </dt> <dd>
<p>In <code>range(60)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.time.microsecond">
<code>time.microsecond</code> </dt> <dd>
<p>In <code>range(1000000)</code>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.time.tzinfo">
<code>time.tzinfo</code> </dt> <dd>
<p>The object passed as the tzinfo argument to the <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> constructor, or <code>None</code> if none was passed.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.time.fold">
<code>time.fold</code> </dt> <dd>
<p>In <code>[0, 1]</code>. Used to disambiguate wall times during a repeated interval. (A repeated interval occurs when clocks are rolled back at the end of daylight saving time or when the UTC offset for the current zone is decreased for political reasons.) The value 0 (1) represents the earlier (later) of the two moments with the same wall time representation.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <p><a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> objects support comparison of <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> to <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a>, where <em>a</em> is considered less than <em>b</em> when <em>a</em> precedes <em>b</em> in time. If one comparand is naive and the other is aware, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised if an order comparison is attempted. For equality comparisons, naive instances are never equal to aware instances.</p> <p>If both comparands are aware, and have the same <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code>tzinfo</code></a> attribute, the common <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code>tzinfo</code></a> attribute is ignored and the base times are compared. If both comparands are aware and have different <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code>tzinfo</code></a> attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from <code>self.utcoffset()</code>). In order to stop mixed-type comparisons from falling back to the default comparison by object address, when a <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object is compared to an object of a different type, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised unless the comparison is <code>==</code> or <code>!=</code>. The latter cases return <a class="reference internal" href="constants#False" title="False"><code>False</code></a> or <a class="reference internal" href="constants#True" title="True"><code>True</code></a>, respectively.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Equality comparisons between aware and naive <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> instances don’t raise <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> </div> <p>In Boolean contexts, a <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object is always considered to be true.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Before Python 3.5, a <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object was considered to be false if it represented midnight in UTC. This behavior was considered obscure and error-prone and has been removed in Python 3.5. See <a class="reference external" href="https://bugs.python.org/issue?@action=redirect&amp;bpo=13936">bpo-13936</a> for full details.</p> </div> <p>Other constructor:</p> <dl class="py method"> <dt class="sig sig-object py" id="datetime.time.fromisoformat">
<code>classmethod time.fromisoformat(time_string)</code> </dt> <dd>
<p>Return a <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> corresponding to a <em>time_string</em> in any valid ISO 8601 format, with the following exceptions:</p> <ol class="arabic simple"> <li>Time zone offsets may have fractional seconds.</li> <li>The leading <code>T</code>, normally required in cases where there may be ambiguity between a date and a time, is not required.</li> <li>Fractional seconds may have any number of digits (anything beyond 6 will be truncated).</li> <li>Fractional hours and minutes are not supported.</li> </ol> <p>Examples:</p> <pre data-language="python">.. doctest::
</pre> <pre data-language="python">&gt;&gt;&gt; from datetime import time
&gt;&gt;&gt; time.fromisoformat('04:23:01')
datetime.time(4, 23, 1)
&gt;&gt;&gt; time.fromisoformat('T04:23:01')
datetime.time(4, 23, 1)
&gt;&gt;&gt; time.fromisoformat('T042301')
datetime.time(4, 23, 1)
&gt;&gt;&gt; time.fromisoformat('04:23:01.000384')
datetime.time(4, 23, 1, 384)
&gt;&gt;&gt; time.fromisoformat('04:23:01,000384')
datetime.time(4, 23, 1, 384)
&gt;&gt;&gt; time.fromisoformat('04:23:01+04:00')
datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
&gt;&gt;&gt; time.fromisoformat('04:23:01Z')
datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)
&gt;&gt;&gt; time.fromisoformat('04:23:01+00:00')
datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Previously, this method only supported formats that could be emitted by <a class="reference internal" href="#datetime.time.isoformat" title="datetime.time.isoformat"><code>time.isoformat()</code></a>.</p> </div> </dd>
</dl> <p>Instance methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="datetime.time.replace">
<code>time.replace(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)</code> </dt> <dd>
<p>Return a <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> with the same value, except for those attributes given new values by whichever keyword arguments are specified. Note that <code>tzinfo=None</code> can be specified to create a naive <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> from an aware <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a>, without conversion of the time data.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6: </span>Added the <code>fold</code> argument.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.time.isoformat">
<code>time.isoformat(timespec='auto')</code> </dt> <dd>
<p>Return a string representing the time in ISO 8601 format, one of:</p> <ul class="simple"> <li>
<code>HH:MM:SS.ffffff</code>, if <a class="reference internal" href="#datetime.time.microsecond" title="datetime.time.microsecond"><code>microsecond</code></a> is not 0</li> <li>
<code>HH:MM:SS</code>, if <a class="reference internal" href="#datetime.time.microsecond" title="datetime.time.microsecond"><code>microsecond</code></a> is 0</li> <li>
<code>HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]</code>, if <a class="reference internal" href="#datetime.time.utcoffset" title="datetime.time.utcoffset"><code>utcoffset()</code></a> does not return <code>None</code>
</li> <li>
<code>HH:MM:SS+HH:MM[:SS[.ffffff]]</code>, if <a class="reference internal" href="#datetime.time.microsecond" title="datetime.time.microsecond"><code>microsecond</code></a> is 0 and <a class="reference internal" href="#datetime.time.utcoffset" title="datetime.time.utcoffset"><code>utcoffset()</code></a> does not return <code>None</code>
</li> </ul> <p>The optional argument <em>timespec</em> specifies the number of additional components of the time to include (the default is <code>'auto'</code>). It can be one of the following:</p> <ul class="simple"> <li>
<code>'auto'</code>: Same as <code>'seconds'</code> if <a class="reference internal" href="#datetime.time.microsecond" title="datetime.time.microsecond"><code>microsecond</code></a> is 0, same as <code>'microseconds'</code> otherwise.</li> <li>
<code>'hours'</code>: Include the <a class="reference internal" href="#datetime.time.hour" title="datetime.time.hour"><code>hour</code></a> in the two-digit <code>HH</code> format.</li> <li>
<code>'minutes'</code>: Include <a class="reference internal" href="#datetime.time.hour" title="datetime.time.hour"><code>hour</code></a> and <a class="reference internal" href="#datetime.time.minute" title="datetime.time.minute"><code>minute</code></a> in <code>HH:MM</code> format.</li> <li>
<code>'seconds'</code>: Include <a class="reference internal" href="#datetime.time.hour" title="datetime.time.hour"><code>hour</code></a>, <a class="reference internal" href="#datetime.time.minute" title="datetime.time.minute"><code>minute</code></a>, and <a class="reference internal" href="#datetime.time.second" title="datetime.time.second"><code>second</code></a> in <code>HH:MM:SS</code> format.</li> <li>
<code>'milliseconds'</code>: Include full time, but truncate fractional second part to milliseconds. <code>HH:MM:SS.sss</code> format.</li> <li>
<code>'microseconds'</code>: Include full time in <code>HH:MM:SS.ffffff</code> format.</li> </ul> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Excluded time components are truncated, not rounded.</p> </div> <p><a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> will be raised on an invalid <em>timespec</em> argument.</p> <p>Example:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import time
&gt;&gt;&gt; time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
'12:34'
&gt;&gt;&gt; dt = time(hour=12, minute=34, second=56, microsecond=0)
&gt;&gt;&gt; dt.isoformat(timespec='microseconds')
'12:34:56.000000'
&gt;&gt;&gt; dt.isoformat(timespec='auto')
'12:34:56'
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6: </span>Added the <em>timespec</em> argument.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.time.__str__">
<code>time.__str__()</code> </dt> <dd>
<p>For a time <em>t</em>, <code>str(t)</code> is equivalent to <code>t.isoformat()</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.time.strftime">
<code>time.strftime(format)</code> </dt> <dd>
<p>Return a string representing the time, controlled by an explicit format string. See also <a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a> and <a class="reference internal" href="#datetime.time.isoformat" title="datetime.time.isoformat"><code>time.isoformat()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.time.__format__">
<code>time.__format__(format)</code> </dt> <dd>
<p>Same as <a class="reference internal" href="#datetime.time.strftime" title="datetime.time.strftime"><code>time.strftime()</code></a>. This makes it possible to specify a format string for a <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object in <a class="reference internal" href="../reference/lexical_analysis#f-strings"><span class="std std-ref">formatted string literals</span></a> and when using <a class="reference internal" href="stdtypes#str.format" title="str.format"><code>str.format()</code></a>. See also <a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a> and <a class="reference internal" href="#datetime.time.isoformat" title="datetime.time.isoformat"><code>time.isoformat()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.time.utcoffset">
<code>time.utcoffset()</code> </dt> <dd>
<p>If <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code>tzinfo</code></a> is <code>None</code>, returns <code>None</code>, else returns <code>self.tzinfo.utcoffset(None)</code>, and raises an exception if the latter doesn’t return <code>None</code> or a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object with magnitude less than one day.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The UTC offset is not restricted to a whole number of minutes.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.time.dst">
<code>time.dst()</code> </dt> <dd>
<p>If <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code>tzinfo</code></a> is <code>None</code>, returns <code>None</code>, else returns <code>self.tzinfo.dst(None)</code>, and raises an exception if the latter doesn’t return <code>None</code>, or a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object with magnitude less than one day.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The DST offset is not restricted to a whole number of minutes.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.time.tzname">
<code>time.tzname()</code> </dt> <dd>
<p>If <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code>tzinfo</code></a> is <code>None</code>, returns <code>None</code>, else returns <code>self.tzinfo.tzname(None)</code>, or raises an exception if the latter doesn’t return <code>None</code> or a string object.</p> </dd>
</dl> <section id="examples-of-usage-time"> <h3>Examples of Usage: <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a>
</h3> <p>Examples of working with a <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import time, tzinfo, timedelta
&gt;&gt;&gt; class TZ1(tzinfo):
...     def utcoffset(self, dt):
...         return timedelta(hours=1)
...     def dst(self, dt):
...         return timedelta(0)
...     def tzname(self,dt):
...         return "+01:00"
...     def  __repr__(self):
...         return f"{self.__class__.__name__}()"
...
&gt;&gt;&gt; t = time(12, 10, 30, tzinfo=TZ1())
&gt;&gt;&gt; t
datetime.time(12, 10, 30, tzinfo=TZ1())
&gt;&gt;&gt; t.isoformat()
'12:10:30+01:00'
&gt;&gt;&gt; t.dst()
datetime.timedelta(0)
&gt;&gt;&gt; t.tzname()
'+01:00'
&gt;&gt;&gt; t.strftime("%H:%M:%S %Z")
'12:10:30 +01:00'
&gt;&gt;&gt; 'The {} is {:%H:%M}.'.format("time", t)
'The time is 12:10.'
</pre> </section> </section> <section id="tzinfo-objects"> <span id="datetime-tzinfo"></span><h2>tzinfo Objects</h2> <dl class="py class"> <dt class="sig sig-object py" id="datetime.tzinfo">
<code>class datetime.tzinfo</code> </dt> <dd>
<p>This is an abstract base class, meaning that this class should not be instantiated directly. Define a subclass of <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> to capture information about a particular time zone.</p> <p>An instance of (a concrete subclass of) <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> can be passed to the constructors for <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> and <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> objects. The latter objects view their attributes as being in local time, and the <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> object supports methods revealing offset of local time from UTC, the name of the time zone, and DST offset, all relative to a date or time object passed to them.</p> <p>You need to derive a concrete subclass, and (at least) supply implementations of the standard <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> methods needed by the <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> methods you use. The <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code>datetime</code></a> module provides <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a>, a simple concrete subclass of <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> which can represent timezones with fixed offset from UTC such as UTC itself or North American EST and EDT.</p> <p>Special requirement for pickling: A <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass must have an <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method that can be called with no arguments, otherwise it can be pickled but possibly not unpickled again. This is a technical requirement that may be relaxed in the future.</p> <p>A concrete subclass of <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> may need to implement the following methods. Exactly which methods are needed depends on the uses made of aware <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code>datetime</code></a> objects. If in doubt, simply implement all of them.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.tzinfo.utcoffset">
<code>tzinfo.utcoffset(dt)</code> </dt> <dd>
<p>Return offset of local time from UTC, as a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object that is positive east of UTC. If local time is west of UTC, this should be negative.</p> <p>This represents the <em>total</em> offset from UTC; for example, if a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> object represents both time zone and DST adjustments, <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code>utcoffset()</code></a> should return their sum. If the UTC offset isn’t known, return <code>None</code>. Else the value returned must be a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object strictly between <code>-timedelta(hours=24)</code> and <code>timedelta(hours=24)</code> (the magnitude of the offset must be less than one day). Most implementations of <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code>utcoffset()</code></a> will probably look like one of these two:</p> <pre data-language="python">return CONSTANT                 # fixed-offset class
return CONSTANT + self.dst(dt)  # daylight-aware class
</pre> <p>If <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code>utcoffset()</code></a> does not return <code>None</code>, <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code>dst()</code></a> should not return <code>None</code> either.</p> <p>The default implementation of <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code>utcoffset()</code></a> raises <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The UTC offset is not restricted to a whole number of minutes.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.tzinfo.dst">
<code>tzinfo.dst(dt)</code> </dt> <dd>
<p>Return the daylight saving time (DST) adjustment, as a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object or <code>None</code> if DST information isn’t known.</p> <p>Return <code>timedelta(0)</code> if DST is not in effect. If DST is in effect, return the offset as a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object (see <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code>utcoffset()</code></a> for details). Note that DST offset, if applicable, has already been added to the UTC offset returned by <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code>utcoffset()</code></a>, so there’s no need to consult <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code>dst()</code></a> unless you’re interested in obtaining DST info separately. For example, <a class="reference internal" href="#datetime.datetime.timetuple" title="datetime.datetime.timetuple"><code>datetime.timetuple()</code></a> calls its <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code>tzinfo</code></a> attribute’s <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code>dst()</code></a> method to determine how the <code>tm_isdst</code> flag should be set, and <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code>tzinfo.fromutc()</code></a> calls <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code>dst()</code></a> to account for DST changes when crossing time zones.</p> <p>An instance <em>tz</em> of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass that models both standard and daylight times must be consistent in this sense:</p> <p><code>tz.utcoffset(dt) - tz.dst(dt)</code></p> <p>must return the same result for every <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> <em>dt</em> with <code>dt.tzinfo ==
tz</code> For sane <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclasses, this expression yields the time zone’s “standard offset”, which should not depend on the date or the time, but only on geographic location. The implementation of <a class="reference internal" href="#datetime.datetime.astimezone" title="datetime.datetime.astimezone"><code>datetime.astimezone()</code></a> relies on this, but cannot detect violations; it’s the programmer’s responsibility to ensure it. If a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass cannot guarantee this, it may be able to override the default implementation of <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code>tzinfo.fromutc()</code></a> to work correctly with <code>astimezone()</code> regardless.</p> <p>Most implementations of <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code>dst()</code></a> will probably look like one of these two:</p> <pre data-language="python">def dst(self, dt):
    # a fixed-offset class:  doesn't account for DST
    return timedelta(0)
</pre> <p>or:</p> <pre data-language="python">def dst(self, dt):
    # Code to set dston and dstoff to the time zone's DST
    # transition times based on the input dt.year, and expressed
    # in standard local time.

    if dston &lt;= dt.replace(tzinfo=None) &lt; dstoff:
        return timedelta(hours=1)
    else:
        return timedelta(0)
</pre> <p>The default implementation of <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code>dst()</code></a> raises <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The DST offset is not restricted to a whole number of minutes.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.tzinfo.tzname">
<code>tzinfo.tzname(dt)</code> </dt> <dd>
<p>Return the time zone name corresponding to the <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object <em>dt</em>, as a string. Nothing about string names is defined by the <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code>datetime</code></a> module, and there’s no requirement that it mean anything in particular. For example, “GMT”, “UTC”, “-500”, “-5:00”, “EDT”, “US/Eastern”, “America/New York” are all valid replies. Return <code>None</code> if a string name isn’t known. Note that this is a method rather than a fixed string primarily because some <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclasses will wish to return different names depending on the specific value of <em>dt</em> passed, especially if the <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> class is accounting for daylight time.</p> <p>The default implementation of <a class="reference internal" href="#datetime.tzinfo.tzname" title="datetime.tzinfo.tzname"><code>tzname()</code></a> raises <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> </dd>
</dl> <p>These methods are called by a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> or <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object, in response to their methods of the same names. A <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object passes itself as the argument, and a <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> object passes <code>None</code> as the argument. A <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass’s methods should therefore be prepared to accept a <em>dt</em> argument of <code>None</code>, or of class <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a>.</p> <p>When <code>None</code> is passed, it’s up to the class designer to decide the best response. For example, returning <code>None</code> is appropriate if the class wishes to say that time objects don’t participate in the <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> protocols. It may be more useful for <code>utcoffset(None)</code> to return the standard UTC offset, as there is no other convention for discovering the standard offset.</p> <p>When a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object is passed in response to a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> method, <code>dt.tzinfo</code> is the same object as <em>self</em>. <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> methods can rely on this, unless user code calls <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> methods directly. The intent is that the <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> methods interpret <em>dt</em> as being in local time, and not need worry about objects in other timezones.</p> <p>There is one more <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> method that a subclass may wish to override:</p> <dl class="py method"> <dt class="sig sig-object py" id="datetime.tzinfo.fromutc">
<code>tzinfo.fromutc(dt)</code> </dt> <dd>
<p>This is called from the default <a class="reference internal" href="#datetime.datetime.astimezone" title="datetime.datetime.astimezone"><code>datetime.astimezone()</code></a> implementation. When called from that, <code>dt.tzinfo</code> is <em>self</em>, and <em>dt</em>’s date and time data are to be viewed as expressing a UTC time. The purpose of <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code>fromutc()</code></a> is to adjust the date and time data, returning an equivalent datetime in <em>self</em>’s local time.</p> <p>Most <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclasses should be able to inherit the default <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code>fromutc()</code></a> implementation without problems. It’s strong enough to handle fixed-offset time zones, and time zones accounting for both standard and daylight time, and the latter even if the DST transition times differ in different years. An example of a time zone the default <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code>fromutc()</code></a> implementation may not handle correctly in all cases is one where the standard offset (from UTC) depends on the specific date and time passed, which can happen for political reasons. The default implementations of <code>astimezone()</code> and <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code>fromutc()</code></a> may not produce the result you want if the result is one of the hours straddling the moment the standard offset changes.</p> <p>Skipping code for error cases, the default <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code>fromutc()</code></a> implementation acts like:</p> <pre data-language="python">def fromutc(self, dt):
    # raise ValueError error if dt.tzinfo is not self
    dtoff = dt.utcoffset()
    dtdst = dt.dst()
    # raise ValueError if dtoff is None or dtdst is None
    delta = dtoff - dtdst  # this is self's standard offset
    if delta:
        dt += delta   # convert to standard local time
        dtdst = dt.dst()
        # raise ValueError if dtdst is None
    if dtdst:
        return dt + dtdst
    else:
        return dt
</pre> </dd>
</dl> <p>In the following <a class="reference download internal" download="" href="../_downloads/6dc1f3f4f0e6ca13cb42ddf4d6cbc8af/tzinfo_examples.py"><code>tzinfo_examples.py</code></a> file there are some examples of <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> classes:</p> <pre data-language="python">from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)
HOUR = timedelta(hours=1)
SECOND = timedelta(seconds=1)

# A class capturing the platform's idea of local time.
# (May result in wrong values on historical times in
#  timezones where UTC offset and/or the DST rules had
#  changed in the past.)
import time as _time

STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
    DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
    DSTOFFSET = STDOFFSET

DSTDIFF = DSTOFFSET - STDOFFSET

class LocalTimezone(tzinfo):

    def fromutc(self, dt):
        assert dt.tzinfo is self
        stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND
        args = _time.localtime(stamp)[:6]
        dst_diff = DSTDIFF // SECOND
        # Detect fold
        fold = (args == _time.localtime(stamp - dst_diff))
        return datetime(*args, microsecond=dt.microsecond,
                        tzinfo=self, fold=fold)

    def utcoffset(self, dt):
        if self._isdst(dt):
            return DSTOFFSET
        else:
            return STDOFFSET

    def dst(self, dt):
        if self._isdst(dt):
            return DSTDIFF
        else:
            return ZERO

    def tzname(self, dt):
        return _time.tzname[self._isdst(dt)]

    def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, 0)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst &gt; 0

Local = LocalTimezone()


# A complete implementation of current DST rules for major US time zones.

def first_sunday_on_or_after(dt):
    days_to_go = 6 - dt.weekday()
    if days_to_go:
        dt += timedelta(days_to_go)
    return dt


# US DST Rules
#
# This is a simplified (i.e., wrong for a few cases) set of rules for US
# DST start and end times. For a complete and up-to-date set of DST rules
# and timezone definitions, visit the Olson Database (or try pytz):
# http://www.twinsun.com/tz/tz-link.htm
# https://sourceforge.net/projects/pytz/ (might not be up-to-date)
#
# In the US, since 2007, DST starts at 2am (standard time) on the second
# Sunday in March, which is the first Sunday on or after Mar 8.
DSTSTART_2007 = datetime(1, 3, 8, 2)
# and ends at 2am (DST time) on the first Sunday of Nov.
DSTEND_2007 = datetime(1, 11, 1, 2)
# From 1987 to 2006, DST used to start at 2am (standard time) on the first
# Sunday in April and to end at 2am (DST time) on the last
# Sunday of October, which is the first Sunday on or after Oct 25.
DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
DSTEND_1987_2006 = datetime(1, 10, 25, 2)
# From 1967 to 1986, DST used to start at 2am (standard time) on the last
# Sunday in April (the one on or after April 24) and to end at 2am (DST time)
# on the last Sunday of October, which is the first Sunday
# on or after Oct 25.
DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
DSTEND_1967_1986 = DSTEND_1987_2006

def us_dst_range(year):
    # Find start and end times for US DST. For years before 1967, return
    # start = end for no DST.
    if 2006 &lt; year:
        dststart, dstend = DSTSTART_2007, DSTEND_2007
    elif 1986 &lt; year &lt; 2007:
        dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
    elif 1966 &lt; year &lt; 1987:
        dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
    else:
        return (datetime(year, 1, 1), ) * 2

    start = first_sunday_on_or_after(dststart.replace(year=year))
    end = first_sunday_on_or_after(dstend.replace(year=year))
    return start, end


class USTimeZone(tzinfo):

    def __init__(self, hours, reprname, stdname, dstname):
        self.stdoffset = timedelta(hours=hours)
        self.reprname = reprname
        self.stdname = stdname
        self.dstname = dstname

    def __repr__(self):
        return self.reprname

    def tzname(self, dt):
        if self.dst(dt):
            return self.dstname
        else:
            return self.stdname

    def utcoffset(self, dt):
        return self.stdoffset + self.dst(dt)

    def dst(self, dt):
        if dt is None or dt.tzinfo is None:
            # An exception may be sensible here, in one or both cases.
            # It depends on how you want to treat them.  The default
            # fromutc() implementation (called by the default astimezone()
            # implementation) passes a datetime with dt.tzinfo is self.
            return ZERO
        assert dt.tzinfo is self
        start, end = us_dst_range(dt.year)
        # Can't compare naive to aware objects, so strip the timezone from
        # dt first.
        dt = dt.replace(tzinfo=None)
        if start + HOUR &lt;= dt &lt; end - HOUR:
            # DST is in effect.
            return HOUR
        if end - HOUR &lt;= dt &lt; end:
            # Fold (an ambiguous hour): use dt.fold to disambiguate.
            return ZERO if dt.fold else HOUR
        if start &lt;= dt &lt; start + HOUR:
            # Gap (a non-existent hour): reverse the fold rule.
            return HOUR if dt.fold else ZERO
        # DST is off.
        return ZERO

    def fromutc(self, dt):
        assert dt.tzinfo is self
        start, end = us_dst_range(dt.year)
        start = start.replace(tzinfo=self)
        end = end.replace(tzinfo=self)
        std_time = dt + self.stdoffset
        dst_time = std_time + HOUR
        if end &lt;= dst_time &lt; end + HOUR:
            # Repeated hour
            return std_time.replace(fold=1)
        if std_time &lt; start or dst_time &gt;= end:
            # Standard time
            return std_time
        if start &lt;= std_time &lt; end - HOUR:
            # Daylight saving time
            return dst_time


Eastern  = USTimeZone(-5, "Eastern",  "EST", "EDT")
Central  = USTimeZone(-6, "Central",  "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific  = USTimeZone(-8, "Pacific",  "PST", "PDT")
</pre> <p>Note that there are unavoidable subtleties twice per year in a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass accounting for both standard and daylight time, at the DST transition points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the minute after 1:59 (EST) on the second Sunday in March, and ends the minute after 1:59 (EDT) on the first Sunday in November:</p> <pre data-language="python">  UTC   3:MM  4:MM  5:MM  6:MM  7:MM  8:MM
  EST  22:MM 23:MM  0:MM  1:MM  2:MM  3:MM
  EDT  23:MM  0:MM  1:MM  2:MM  3:MM  4:MM

start  22:MM 23:MM  0:MM  1:MM  3:MM  4:MM

  end  23:MM  0:MM  1:MM  1:MM  2:MM  3:MM
</pre> <p>When DST starts (the “start” line), the local wall clock leaps from 1:59 to 3:00. A wall time of the form 2:MM doesn’t really make sense on that day, so <code>astimezone(Eastern)</code> won’t deliver a result with <code>hour == 2</code> on the day DST begins. For example, at the Spring forward transition of 2016, we get:</p> <pre data-language="python">&gt;&gt;&gt; from datetime import datetime, timezone
&gt;&gt;&gt; from tzinfo_examples import HOUR, Eastern
&gt;&gt;&gt; u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
&gt;&gt;&gt; for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname())
...
05:00:00 UTC = 00:00:00 EST
06:00:00 UTC = 01:00:00 EST
07:00:00 UTC = 03:00:00 EDT
08:00:00 UTC = 04:00:00 EDT
</pre> <p>When DST ends (the “end” line), there’s a potentially worse problem: there’s an hour that can’t be spelled unambiguously in local wall time: the last hour of daylight time. In Eastern, that’s times of the form 5:MM UTC on the day daylight time ends. The local wall clock leaps from 1:59 (daylight time) back to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous. <code>astimezone()</code> mimics the local clock’s behavior by mapping two adjacent UTC hours into the same local hour then. In the Eastern example, UTC times of the form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times have the <a class="reference internal" href="#datetime.datetime.fold" title="datetime.datetime.fold"><code>fold</code></a> attribute set to 0 and the later times have it set to 1. For example, at the Fall back transition of 2016, we get:</p> <pre data-language="python">&gt;&gt;&gt; u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
&gt;&gt;&gt; for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0
</pre> <p>Note that the <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> instances that differ only by the value of the <a class="reference internal" href="#datetime.datetime.fold" title="datetime.datetime.fold"><code>fold</code></a> attribute are considered equal in comparisons.</p> <p>Applications that can’t bear wall-time ambiguities should explicitly check the value of the <a class="reference internal" href="#datetime.datetime.fold" title="datetime.datetime.fold"><code>fold</code></a> attribute or avoid using hybrid <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclasses; there are no ambiguities when using <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a>, or any other fixed-offset <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a> subclass (such as a class representing only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).</p> <div class="admonition seealso"> <p class="admonition-title">See also</p>  <dl> <dt>
<code></code> <a class="reference internal" href="zoneinfo#module-zoneinfo" title="zoneinfo: IANA time zone support"><code>zoneinfo</code></a>
</dt>
<dd>
<p>The <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code>datetime</code></a> module has a basic <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a> class (for handling arbitrary fixed offsets from UTC) and its <a class="reference internal" href="#datetime.timezone.utc" title="datetime.timezone.utc"><code>timezone.utc</code></a> attribute (a UTC timezone instance).</p> <p><code>zoneinfo</code> brings the <em>IANA timezone database</em> (also known as the Olson database) to Python, and its usage is recommended.</p> </dd> </dl>  <dl class="simple"> <dt><a class="reference external" href="https://www.iana.org/time-zones">IANA timezone database</a></dt>
<dd>
<p>The Time Zone Database (often called tz, tzdata or zoneinfo) contains code and data that represent the history of local time for many representative locations around the globe. It is updated periodically to reflect changes made by political bodies to time zone boundaries, UTC offsets, and daylight-saving rules.</p> </dd> </dl> </div> </section> <section id="timezone-objects"> <span id="datetime-timezone"></span><h2>timezone Objects</h2> <p>The <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a> class is a subclass of <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code>tzinfo</code></a>, each instance of which represents a timezone defined by a fixed offset from UTC.</p> <p>Objects of this class cannot be used to represent timezone information in the locations where different offsets are used in different days of the year or where historical changes have been made to civil time.</p> <dl class="py class"> <dt class="sig sig-object py" id="datetime.timezone">
<code>class datetime.timezone(offset, name=None)</code> </dt> <dd>
<p>The <em>offset</em> argument must be specified as a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> object representing the difference between the local time and UTC. It must be strictly between <code>-timedelta(hours=24)</code> and <code>timedelta(hours=24)</code>, otherwise <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised.</p> <p>The <em>name</em> argument is optional. If specified it must be a string that will be used as the value returned by the <a class="reference internal" href="#datetime.datetime.tzname" title="datetime.datetime.tzname"><code>datetime.tzname()</code></a> method.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The UTC offset is not restricted to a whole number of minutes.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.timezone.utcoffset">
<code>timezone.utcoffset(dt)</code> </dt> <dd>
<p>Return the fixed value specified when the <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a> instance is constructed.</p> <p>The <em>dt</em> argument is ignored. The return value is a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code>timedelta</code></a> instance equal to the difference between the local time and UTC.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The UTC offset is not restricted to a whole number of minutes.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.timezone.tzname">
<code>timezone.tzname(dt)</code> </dt> <dd>
<p>Return the fixed value specified when the <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a> instance is constructed.</p> <p>If <em>name</em> is not provided in the constructor, the name returned by <code>tzname(dt)</code> is generated from the value of the <code>offset</code> as follows. If <em>offset</em> is <code>timedelta(0)</code>, the name is “UTC”, otherwise it is a string in the format <code>UTC±HH:MM</code>, where ± is the sign of <code>offset</code>, HH and MM are two digits of <code>offset.hours</code> and <code>offset.minutes</code> respectively.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Name generated from <code>offset=timedelta(0)</code> is now plain <code>'UTC'</code>, not <code>'UTC+00:00'</code>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.timezone.dst">
<code>timezone.dst(dt)</code> </dt> <dd>
<p>Always returns <code>None</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="datetime.timezone.fromutc">
<code>timezone.fromutc(dt)</code> </dt> <dd>
<p>Return <code>dt + offset</code>. The <em>dt</em> argument must be an aware <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> instance, with <code>tzinfo</code> set to <code>self</code>.</p> </dd>
</dl> <p>Class attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="datetime.timezone.utc">
<code>timezone.utc</code> </dt> <dd>
<p>The UTC timezone, <code>timezone(timedelta(0))</code>.</p> </dd>
</dl> </section> <section id="strftime-and-strptime-behavior"> <span id="strftime-strptime-behavior"></span><span id="index-0"></span><h2>
<code>strftime()</code> and <code>strptime()</code> Behavior</h2> <p><a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a>, <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a>, and <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> objects all support a <code>strftime(format)</code> method, to create a string representing the time under the control of an explicit format string.</p> <p>Conversely, the <a class="reference internal" href="#datetime.datetime.strptime" title="datetime.datetime.strptime"><code>datetime.strptime()</code></a> class method creates a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object from a string representing a date and time and a corresponding format string.</p> <p>The table below provides a high-level comparison of <code>strftime()</code> versus <code>strptime()</code>:</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"></th> <th class="head"><p><code>strftime</code></p></th> <th class="head"><p><code>strptime</code></p></th> </tr> </thead>  <tr>
<td><p>Usage</p></td> <td><p>Convert object to a string according to a given format</p></td> <td><p>Parse a string into a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object given a corresponding format</p></td> </tr> <tr>
<td><p>Type of method</p></td> <td><p>Instance method</p></td> <td><p>Class method</p></td> </tr> <tr>
<td><p>Method of</p></td> <td><p><a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a>; <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a>; <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a></p></td> <td><p><a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a></p></td> </tr> <tr>
<td><p>Signature</p></td> <td><p><code>strftime(format)</code></p></td> <td><p><code>strptime(date_string, format)</code></p></td> </tr>  </table>   <section id="strftime-and-strptime-format-codes"> <span id="format-codes"></span><h3>
<code>strftime()</code> and <code>strptime()</code> Format Codes</h3> <p>These methods accept format codes that can be used to parse and format dates:</p> <pre data-language="python">&gt;&gt;&gt; datetime.strptime('31/01/22 23:59:59.999999',
...                   '%d/%m/%y %H:%M:%S.%f')
datetime.datetime(2022, 1, 31, 23, 59, 59, 999999)
&gt;&gt;&gt; _.strftime('%a %d %b %Y, %I:%M%p')
'Mon 31 Jan 2022, 11:59PM'
</pre> <p>The following is a list of all the format codes that the 1989 C standard requires, and these work on all platforms with a standard C implementation.</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Directive</p></th> <th class="head"><p>Meaning</p></th> <th class="head"><p>Example</p></th> <th class="head"><p>Notes</p></th> </tr> </thead>  <tr>
<td><p><code>%a</code></p></td> <td><p>Weekday as locale’s abbreviated name.</p></td> <td> </td> <td><p>(1)</p></td> </tr> <tr>
<td><p><code>%A</code></p></td> <td><p>Weekday as locale’s full name.</p></td> <td> </td> <td><p>(1)</p></td> </tr> <tr>
<td><p><code>%w</code></p></td> <td><p>Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.</p></td> <td><p>0, 1, …, 6</p></td> <td></td> </tr> <tr>
<td><p><code>%d</code></p></td> <td><p>Day of the month as a zero-padded decimal number.</p></td> <td><p>01, 02, …, 31</p></td> <td><p>(9)</p></td> </tr> <tr>
<td><p><code>%b</code></p></td> <td><p>Month as locale’s abbreviated name.</p></td> <td> </td> <td><p>(1)</p></td> </tr> <tr>
<td><p><code>%B</code></p></td> <td><p>Month as locale’s full name.</p></td> <td> </td> <td><p>(1)</p></td> </tr> <tr>
<td><p><code>%m</code></p></td> <td><p>Month as a zero-padded decimal number.</p></td> <td><p>01, 02, …, 12</p></td> <td><p>(9)</p></td> </tr> <tr>
<td><p><code>%y</code></p></td> <td><p>Year without century as a zero-padded decimal number.</p></td> <td><p>00, 01, …, 99</p></td> <td><p>(9)</p></td> </tr> <tr>
<td><p><code>%Y</code></p></td> <td><p>Year with century as a decimal number.</p></td> <td><p>0001, 0002, …, 2013, 2014, …, 9998, 9999</p></td> <td><p>(2)</p></td> </tr> <tr>
<td><p><code>%H</code></p></td> <td><p>Hour (24-hour clock) as a zero-padded decimal number.</p></td> <td><p>00, 01, …, 23</p></td> <td><p>(9)</p></td> </tr> <tr>
<td><p><code>%I</code></p></td> <td><p>Hour (12-hour clock) as a zero-padded decimal number.</p></td> <td><p>01, 02, …, 12</p></td> <td><p>(9)</p></td> </tr> <tr>
<td><p><code>%p</code></p></td> <td><p>Locale’s equivalent of either AM or PM.</p></td> <td> </td> <td><p>(1), (3)</p></td> </tr> <tr>
<td><p><code>%M</code></p></td> <td><p>Minute as a zero-padded decimal number.</p></td> <td><p>00, 01, …, 59</p></td> <td><p>(9)</p></td> </tr> <tr>
<td><p><code>%S</code></p></td> <td><p>Second as a zero-padded decimal number.</p></td> <td><p>00, 01, …, 59</p></td> <td><p>(4), (9)</p></td> </tr> <tr>
<td><p><code>%f</code></p></td> <td><p>Microsecond as a decimal number, zero-padded to 6 digits.</p></td> <td><p>000000, 000001, …, 999999</p></td> <td><p>(5)</p></td> </tr> <tr>
<td><p><code>%z</code></p></td> <td><p>UTC offset in the form <code>±HHMM[SS[.ffffff]]</code> (empty string if the object is naive).</p></td> <td><p>(empty), +0000, -0400, +1030, +063415, -030712.345216</p></td> <td><p>(6)</p></td> </tr> <tr>
<td><p><code>%Z</code></p></td> <td><p>Time zone name (empty string if the object is naive).</p></td> <td><p>(empty), UTC, GMT</p></td> <td><p>(6)</p></td> </tr> <tr>
<td><p><code>%j</code></p></td> <td><p>Day of the year as a zero-padded decimal number.</p></td> <td><p>001, 002, …, 366</p></td> <td><p>(9)</p></td> </tr> <tr>
<td><p><code>%U</code></p></td> <td><p>Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.</p></td> <td><p>00, 01, …, 53</p></td> <td><p>(7), (9)</p></td> </tr> <tr>
<td><p><code>%W</code></p></td> <td><p>Week number of the year (Monday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Monday are considered to be in week 0.</p></td> <td><p>00, 01, …, 53</p></td> <td><p>(7), (9)</p></td> </tr> <tr>
<td><p><code>%c</code></p></td> <td><p>Locale’s appropriate date and time representation.</p></td> <td> </td> <td><p>(1)</p></td> </tr> <tr>
<td><p><code>%x</code></p></td> <td><p>Locale’s appropriate date representation.</p></td> <td> </td> <td><p>(1)</p></td> </tr> <tr>
<td><p><code>%X</code></p></td> <td><p>Locale’s appropriate time representation.</p></td> <td> </td> <td><p>(1)</p></td> </tr> <tr>
<td><p><code>%%</code></p></td> <td><p>A literal <code>'%'</code> character.</p></td> <td><p>%</p></td> <td></td> </tr>  </table> <p>Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values.</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Directive</p></th> <th class="head"><p>Meaning</p></th> <th class="head"><p>Example</p></th> <th class="head"><p>Notes</p></th> </tr> </thead>  <tr>
<td><p><code>%G</code></p></td> <td><p>ISO 8601 year with century representing the year that contains the greater part of the ISO week (<code>%V</code>).</p></td> <td><p>0001, 0002, …, 2013, 2014, …, 9998, 9999</p></td> <td><p>(8)</p></td> </tr> <tr>
<td><p><code>%u</code></p></td> <td><p>ISO 8601 weekday as a decimal number where 1 is Monday.</p></td> <td><p>1, 2, …, 7</p></td> <td></td> </tr> <tr>
<td><p><code>%V</code></p></td> <td><p>ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4.</p></td> <td><p>01, 02, …, 53</p></td> <td><p>(8), (9)</p></td> </tr> <tr>
<td><p><code>%:z</code></p></td> <td><p>UTC offset in the form <code>±HH:MM[:SS[.ffffff]]</code> (empty string if the object is naive).</p></td> <td><p>(empty), +00:00, -04:00, +10:30, +06:34:15, -03:07:12.345216</p></td> <td><p>(6)</p></td> </tr>  </table> <p>These may not be available on all platforms when used with the <code>strftime()</code> method. The ISO 8601 year and ISO 8601 week directives are not interchangeable with the year and week number directives above. Calling <code>strptime()</code> with incomplete or ambiguous ISO 8601 directives will raise a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>.</p> <p>The full set of format codes supported varies across platforms, because Python calls the platform C library’s <code>strftime()</code> function, and platform variations are common. To see the full set of format codes supported on your platform, consult the <em class="manpage"><a class="manpage reference external" href="https://manpages.debian.org/strftime(3)">strftime(3)</a></em> documentation. There are also differences between platforms in handling of unsupported format specifiers.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6: </span><code>%G</code>, <code>%u</code> and <code>%V</code> were added.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12: </span><code>%:z</code> was added.</p> </div> </section> <section id="technical-detail"> <h3>Technical Detail</h3> <p>Broadly speaking, <code>d.strftime(fmt)</code> acts like the <a class="reference internal" href="time#module-time" title="time: Time access and conversions."><code>time</code></a> module’s <code>time.strftime(fmt, d.timetuple())</code> although not all objects support a <code>timetuple()</code> method.</p> <p>For the <a class="reference internal" href="#datetime.datetime.strptime" title="datetime.datetime.strptime"><code>datetime.strptime()</code></a> class method, the default value is <code>1900-01-01T00:00:00.000</code>: any components not specified in the format string will be pulled from the default value. <a class="footnote-reference brackets" href="#id8" id="id4">4</a></p> <p>Using <code>datetime.strptime(date_string, format)</code> is equivalent to:</p> <pre data-language="python">datetime(*(time.strptime(date_string, format)[0:6]))
</pre> <p>except when the format includes sub-second components or timezone offset information, which are supported in <code>datetime.strptime</code> but are discarded by <code>time.strptime</code>.</p> <p>For <a class="reference internal" href="#datetime.time" title="datetime.time"><code>time</code></a> objects, the format codes for year, month, and day should not be used, as <a class="reference internal" href="time#module-time" title="time: Time access and conversions."><code>time</code></a> objects have no such values. If they’re used anyway, <code>1900</code> is substituted for the year, and <code>1</code> for the month and day.</p> <p>For <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> objects, the format codes for hours, minutes, seconds, and microseconds should not be used, as <a class="reference internal" href="#datetime.date" title="datetime.date"><code>date</code></a> objects have no such values. If they’re used anyway, <code>0</code> is substituted for them.</p> <p>For the same reason, handling of format strings containing Unicode code points that can’t be represented in the charset of the current locale is also platform-dependent. On some platforms such code points are preserved intact in the output, while on others <code>strftime</code> may raise <a class="reference internal" href="exceptions#UnicodeError" title="UnicodeError"><code>UnicodeError</code></a> or return an empty string instead.</p> <p>Notes:</p> <ol class="arabic"> <li>Because the format depends on the current locale, care should be taken when making assumptions about the output value. Field orderings will vary (for example, “month/day/year” versus “day/month/year”), and the output may contain non-ASCII characters.</li> <li>
<p>The <code>strptime()</code> method can parse years in the full [1, 9999] range, but years &lt; 1000 must be zero-filled to 4-digit width.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>In previous versions, <code>strftime()</code> method was restricted to years &gt;= 1900.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>In version 3.2, <code>strftime()</code> method was restricted to years &gt;= 1000.</p> </div> </li> <li>When used with the <code>strptime()</code> method, the <code>%p</code> directive only affects the output hour field if the <code>%I</code> directive is used to parse the hour.</li> <li>Unlike the <a class="reference internal" href="time#module-time" title="time: Time access and conversions."><code>time</code></a> module, the <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code>datetime</code></a> module does not support leap seconds.</li> <li>When used with the <code>strptime()</code> method, the <code>%f</code> directive accepts from one to six digits and zero pads on the right. <code>%f</code> is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).</li> <li>
<p>For a naive object, the <code>%z</code>, <code>%:z</code> and <code>%Z</code> format codes are replaced by empty strings.</p> <p>For an aware object:</p> <dl class="simple"> <dt>
<code>%z</code> </dt>
<dd>
<p><code>utcoffset()</code> is transformed into a string of the form <code>±HHMM[SS[.ffffff]]</code>, where <code>HH</code> is a 2-digit string giving the number of UTC offset hours, <code>MM</code> is a 2-digit string giving the number of UTC offset minutes, <code>SS</code> is a 2-digit string giving the number of UTC offset seconds and <code>ffffff</code> is a 6-digit string giving the number of UTC offset microseconds. The <code>ffffff</code> part is omitted when the offset is a whole number of seconds and both the <code>ffffff</code> and the <code>SS</code> part is omitted when the offset is a whole number of minutes. For example, if <code>utcoffset()</code> returns <code>timedelta(hours=-3, minutes=-30)</code>, <code>%z</code> is replaced with the string <code>'-0330'</code>.</p> </dd> </dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The UTC offset is not restricted to a whole number of minutes.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>When the <code>%z</code> directive is provided to the <code>strptime()</code> method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, <code>'+01:00:00'</code> will be parsed as an offset of one hour. In addition, providing <code>'Z'</code> is identical to <code>'+00:00'</code>.</p> </div> <dl> <dt>
<code>%:z</code> </dt>
<dd>
<p>Behaves exactly as <code>%z</code>, but has a colon separator added between hours, minutes and seconds.</p> </dd> <dt>
<code>%Z</code> </dt>
<dd>
<p>In <code>strftime()</code>, <code>%Z</code> is replaced by an empty string if <code>tzname()</code> returns <code>None</code>; otherwise <code>%Z</code> is replaced by the returned value, which must be a string.</p> <p><code>strptime()</code> only accepts certain values for <code>%Z</code>:</p> <ol class="arabic simple"> <li>any value in <code>time.tzname</code> for your machine’s locale</li> <li>the hard-coded values <code>UTC</code> and <code>GMT</code>
</li> </ol> <p>So someone living in Japan may have <code>JST</code>, <code>UTC</code>, and <code>GMT</code> as valid values, but probably not <code>EST</code>. It will raise <code>ValueError</code> for invalid values.</p> </dd> </dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>When the <code>%z</code> directive is provided to the <code>strptime()</code> method, an aware <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code>datetime</code></a> object will be produced. The <code>tzinfo</code> of the result will be set to a <a class="reference internal" href="#datetime.timezone" title="datetime.timezone"><code>timezone</code></a> instance.</p> </div> </li> <li>When used with the <code>strptime()</code> method, <code>%U</code> and <code>%W</code> are only used in calculations when the day of the week and the calendar year (<code>%Y</code>) are specified.</li> <li>Similar to <code>%U</code> and <code>%W</code>, <code>%V</code> is only used in calculations when the day of the week and the ISO year (<code>%G</code>) are specified in a <code>strptime()</code> format string. Also note that <code>%G</code> and <code>%Y</code> are not interchangeable.</li> <li>When used with the <code>strptime()</code> method, the leading zero is optional for formats <code>%d</code>, <code>%m</code>, <code>%H</code>, <code>%I</code>, <code>%M</code>, <code>%S</code>, <code>%j</code>, <code>%U</code>, <code>%W</code>, and <code>%V</code>. Format <code>%y</code> does require a leading zero.</li> </ol> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="id5">
<code>1</code> </dt> <dd>
<p>If, that is, we ignore the effects of Relativity</p> </dd> <dt class="label" id="id6">
<code>2</code> </dt> <dd>
<p>This matches the definition of the “proleptic Gregorian” calendar in Dershowitz and Reingold’s book <em>Calendrical Calculations</em>, where it’s the base calendar for all computations. See the book for algorithms for converting between proleptic Gregorian ordinals and many other calendar systems.</p> </dd> <dt class="label" id="id7">
<code>3</code> </dt> <dd>
<p>See R. H. van Gent’s <a class="reference external" href="https://web.archive.org/web/20220531051136/https://webspace.science.uu.nl/~gent0113/calendar/isocalendar.htm">guide to the mathematics of the ISO 8601 calendar</a> for a good explanation.</p> </dd> <dt class="label" id="id8">
<code>4</code> </dt> <dd>
<p>Passing <code>datetime.strptime('Feb 29', '%b %d')</code> will fail since <code>1900</code> is not a leap year.</p> </dd> </dl> </section> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/datetime.html" class="_attribution-link">https://docs.python.org/3.12/library/datetime.html</a>
  </p>
</div>