-
-
Notifications
You must be signed in to change notification settings - Fork 34.5k
Expand file tree
/
Copy pathlibdatetime.tex
More file actions
1439 lines (1178 loc) · 54.8 KB
/
libdatetime.tex
File metadata and controls
1439 lines (1178 loc) · 54.8 KB
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
% XXX what order should the types be discussed in?
\section{\module{datetime} ---
Basic date and time types}
\declaremodule{builtin}{datetime}
\modulesynopsis{Basic date and time types.}
\moduleauthor{Tim Peters}{tim@zope.com}
\sectionauthor{Tim Peters}{tim@zope.com}
\sectionauthor{A.M. Kuchling}{amk@amk.ca}
\versionadded{2.3}
The \module{datetime} module supplies classes for manipulating dates
and times in both simple and complex ways. While date and time
arithmetic is supported, the focus of the implementation is on
efficient member extraction for output formatting and manipulation.
There are two kinds of date and time objects: ``naive'' and ``aware''.
This distinction refers to whether the object has any notion of time
zone, daylight saving time, or other kind of algorithmic or political
time adjustment. Whether a naive \class{datetime} object represents
Coordinated Universal Time (UTC), local time, or time in some other
timezone is purely up to the program, just like it's up to the program
whether a particular number represents metres, miles, or mass. Naive
\class{datetime} objects are easy to understand and to work with, at
the cost of ignoring some aspects of reality.
For applications requiring more, \class{datetime} and \class{time}
objects have an optional time zone information member,
\member{tzinfo}, that can contain an instance of a subclass of
the abstract \class{tzinfo} class. These \class{tzinfo} objects
capture information about the offset from UTC time, the time zone
name, and whether Daylight Saving Time is in effect. Note that no
concrete \class{tzinfo} classes are supplied by the \module{datetime}
module. Supporting timezones at whatever level of detail is required
is up to the application. The rules for time adjustment across the
world are more political than rational, and there is no standard
suitable for every application.
The \module{datetime} module exports the following constants:
\begin{datadesc}{MINYEAR}
The smallest year number allowed in a \class{date} or
\class{datetime} object. \constant{MINYEAR}
is \code{1}.
\end{datadesc}
\begin{datadesc}{MAXYEAR}
The largest year number allowed in a \class{date} or \class{datetime}
object. \constant{MAXYEAR} is \code{9999}.
\end{datadesc}
\begin{seealso}
\seemodule{calendar}{General calendar related functions.}
\seemodule{time}{Time access and conversions.}
\end{seealso}
\subsection{Available Types}
\begin{classdesc*}{date}
An idealized naive date, assuming the current Gregorian calendar
always was, and always will be, in effect.
Attributes: \member{year}, \member{month}, and \member{day}.
\end{classdesc*}
\begin{classdesc*}{time}
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: \member{hour}, \member{minute}, \member{second},
\member{microsecond}, and \member{tzinfo}.
\end{classdesc*}
\begin{classdesc*}{datetime}
A combination of a date and a time.
Attributes: \member{year}, \member{month}, \member{day},
\member{hour}, \member{minute}, \member{second},
\member{microsecond}, and \member{tzinfo}.
\end{classdesc*}
\begin{classdesc*}{timedelta}
A duration expressing the difference between two \class{date},
\class{time}, or \class{datetime} instances to microsecond
resolution.
\end{classdesc*}
\begin{classdesc*}{tzinfo}
An abstract base class for time zone information objects. These
are used by the \class{datetime} and \class{time} classes to
provide a customizable notion of time adjustment (for example, to
account for time zone and/or daylight saving time).
\end{classdesc*}
Objects of these types are immutable.
Objects of the \class{date} type are always naive.
An object \var{d} of type \class{time} or \class{datetime} may be
naive or aware. \var{d} is aware if \code{\var{d}.tzinfo} is not
\code{None} and \code{\var{d}.tzinfo.utcoffset(\var{d})} does not return
\code{None}. If \code{\var{d}.tzinfo} is \code{None}, or if
\code{\var{d}.tzinfo} is not \code{None} but
\code{\var{d}.tzinfo.utcoffset(\var{d})} returns \code{None}, \var{d}
is naive.
The distinction between naive and aware doesn't apply to
\class{timedelta} objects.
Subclass relationships:
\begin{verbatim}
object
timedelta
tzinfo
time
date
datetime
\end{verbatim}
\subsection{\class{timedelta} Objects \label{datetime-timedelta}}
A \class{timedelta} object represents a duration, the difference
between two dates or times.
\begin{classdesc}{timedelta}{\optional{days\optional{, seconds\optional{,
microseconds\optional{, milliseconds\optional{,
minutes\optional{, hours\optional{, weeks}}}}}}}}
All arguments are optional and default to \code{0}. Arguments may
be ints, longs, or floats, and may be positive or negative.
Only \var{days}, \var{seconds} and \var{microseconds} are stored
internally. Arguments are converted to those units:
\begin{itemize}
\item A millisecond is converted to 1000 microseconds.
\item A minute is converted to 60 seconds.
\item An hour is converted to 3600 seconds.
\item A week is converted to 7 days.
\end{itemize}
and days, seconds and microseconds are then normalized so that the
representation is unique, with
\begin{itemize}
\item \code{0 <= \var{microseconds} < 1000000}
\item \code{0 <= \var{seconds} < 3600*24} (the number of seconds in one day)
\item \code{-999999999 <= \var{days} <= 999999999}
\end{itemize}
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. If no
argument is a float, the conversion and normalization processes
are exact (no information is lost).
If the normalized value of days lies outside the indicated range,
\exception{OverflowError} is raised.
Note that normalization of negative values may be surprising at first.
For example,
\begin{verbatim}
>>> d = timedelta(microseconds=-1)
>>> (d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)
\end{verbatim}
\end{classdesc}
Class attributes are:
\begin{memberdesc}{min}
The most negative \class{timedelta} object,
\code{timedelta(-999999999)}.
\end{memberdesc}
\begin{memberdesc}{max}
The most positive \class{timedelta} object,
\code{timedelta(days=999999999, hours=23, minutes=59, seconds=59,
microseconds=999999)}.
\end{memberdesc}
\begin{memberdesc}{resolution}
The smallest possible difference between non-equal
\class{timedelta} objects, \code{timedelta(microseconds=1)}.
\end{memberdesc}
Note that, because of normalization, \code{timedelta.max} \textgreater
\code{-timedelta.min}. \code{-timedelta.max} is not representable as
a \class{timedelta} object.
Instance attributes (read-only):
\begin{tableii}{c|l}{code}{Attribute}{Value}
\lineii{days}{Between -999999999 and 999999999 inclusive}
\lineii{seconds}{Between 0 and 86399 inclusive}
\lineii{microseconds}{Between 0 and 999999 inclusive}
\end{tableii}
Supported operations:
% XXX this table is too wide!
\begin{tableii}{c|l}{code}{Operation}{Result}
\lineii{\var{t1} = \var{t2} + \var{t3}}
{Sum of \var{t2} and \var{t3}.
Afterwards \var{t1}-\var{t2} == \var{t3} and \var{t1}-\var{t3}
== \var{t2} are true.
(1)}
\lineii{\var{t1} = \var{t2} - \var{t3}}
{Difference of \var{t2} and \var{t3}.
Afterwards \var{t1} == \var{t2} - \var{t3} and
\var{t2} == \var{t1} + \var{t3} are true.
(1)}
\lineii{\var{t1} = \var{t2} * \var{i} or \var{t1} = \var{i} * \var{t2}}
{Delta multiplied by an integer or long.
Afterwards \var{t1} // i == \var{t2} is true,
provided \code{i != 0}.}
\lineii{}{In general, \var{t1} * i == \var{t1} * (i-1) + \var{t1} is true.
(1)}
\lineii{\var{t1} = \var{t2} // \var{i}}
{The floor is computed and the remainder (if any) is thrown away.
(3)}
\lineii{+\var{t1}}
{Returns a \class{timedelta} object with the same value.
(2)}
\lineii{-\var{t1}}
{equivalent to \class{timedelta}(-\var{t1.days}, -\var{t1.seconds},
-\var{t1.microseconds}), and to \var{t1}* -1.
(1)(4)}
\lineii{abs(\var{t})}
{equivalent to +\var{t} when \code{t.days >= 0}, and to
-\var{t} when \code{t.days < 0}.
(2)}
\end{tableii}
\noindent
Notes:
\begin{description}
\item[(1)]
This is exact, but may overflow.
\item[(2)]
This is exact, and cannot overflow.
\item[(3)]
Division by 0 raises \exception{ZeroDivisionError}.
\item[(4)]
-\var{timedelta.max} is not representable as a \class{timedelta} object.
\end{description}
In addition to the operations listed above \class{timedelta} objects
support certain additions and subtractions with \class{date} and
\class{datetime} objects (see below).
Comparisons of \class{timedelta} objects are supported with the
\class{timedelta} object representing the smaller duration considered
to be the smaller timedelta.
In order to stop mixed-type comparisons from falling back to the
default comparison by object address, when a \class{timedelta} object is
compared to an object of a different type, \exception{TypeError} is
raised unless the comparison is \code{==} or \code{!=}. The latter
cases return \constant{False} or \constant{True}, respectively.
\class{timedelta} objects are hashable (usable as dictionary keys),
support efficient pickling, and in Boolean contexts, a \class{timedelta}
object is considered to be true if and only if it isn't equal to
\code{timedelta(0)}.
\subsection{\class{date} Objects \label{datetime-date}}
A \class{date} object represents a date (year, month and day) in an idealized
calendar, the current Gregorian calendar indefinitely extended in both
directions. January 1 of year 1 is called day number 1, January 2 of year
1 is called day number 2, and so on. This matches the definition of the
"proleptic Gregorian" calendar in Dershowitz and Reingold's book
\citetitle{Calendrical Calculations}, 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.
\begin{classdesc}{date}{year, month, day}
All arguments are required. Arguments may be ints or longs, in the
following ranges:
\begin{itemize}
\item \code{MINYEAR <= \var{year} <= MAXYEAR}
\item \code{1 <= \var{month} <= 12}
\item \code{1 <= \var{day} <= number of days in the given month and year}
\end{itemize}
If an argument outside those ranges is given, \exception{ValueError}
is raised.
\end{classdesc}
Other constructors, all class methods:
\begin{methoddesc}{today}{}
Return the current local date. This is equivalent to
\code{date.fromtimestamp(time.time())}.
\end{methoddesc}
\begin{methoddesc}{fromtimestamp}{timestamp}
Return the local date corresponding to the POSIX timestamp, such
as is returned by \function{time.time()}. This may raise
\exception{ValueError}, if the timestamp is out of the range of
values supported by the platform C \cfunction{localtime()}
function. 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
\method{fromtimestamp()}.
\end{methoddesc}
\begin{methoddesc}{fromordinal}{ordinal}
Return the date corresponding to the proleptic Gregorian ordinal,
where January 1 of year 1 has ordinal 1. \exception{ValueError} is
raised unless \code{1 <= \var{ordinal} <= date.max.toordinal()}.
For any date \var{d}, \code{date.fromordinal(\var{d}.toordinal()) ==
\var{d}}.
\end{methoddesc}
Class attributes:
\begin{memberdesc}{min}
The earliest representable date, \code{date(MINYEAR, 1, 1)}.
\end{memberdesc}
\begin{memberdesc}{max}
The latest representable date, \code{date(MAXYEAR, 12, 31)}.
\end{memberdesc}
\begin{memberdesc}{resolution}
The smallest possible difference between non-equal date
objects, \code{timedelta(days=1)}.
\end{memberdesc}
Instance attributes (read-only):
\begin{memberdesc}{year}
Between \constant{MINYEAR} and \constant{MAXYEAR} inclusive.
\end{memberdesc}
\begin{memberdesc}{month}
Between 1 and 12 inclusive.
\end{memberdesc}
\begin{memberdesc}{day}
Between 1 and the number of days in the given month of the given
year.
\end{memberdesc}
Supported operations:
\begin{tableii}{c|l}{code}{Operation}{Result}
\lineii{\var{date2} = \var{date1} + \var{timedelta}}
{\var{date2} is \code{\var{timedelta}.days} days removed from
\var{date1}. (1)}
\lineii{\var{date2} = \var{date1} - \var{timedelta}}
{Computes \var{date2} such that \code{\var{date2} + \var{timedelta}
== \var{date1}}. (2)}
\lineii{\var{timedelta} = \var{date1} - \var{date2}}
{(3)}
\lineii{\var{date1} < \var{date2}}
{\var{date1} is considered less than \var{date2} when \var{date1}
precedes \var{date2} in time. (4)}
\end{tableii}
Notes:
\begin{description}
\item[(1)]
\var{date2} is moved forward in time if \code{\var{timedelta}.days
> 0}, or backward if \code{\var{timedelta}.days < 0}. Afterward
\code{\var{date2} - \var{date1} == \var{timedelta}.days}.
\code{\var{timedelta}.seconds} and
\code{\var{timedelta}.microseconds} are ignored.
\exception{OverflowError} is raised if \code{\var{date2}.year}
would be smaller than \constant{MINYEAR} or larger than
\constant{MAXYEAR}.
\item[(2)]
This isn't quite equivalent to date1 +
(-timedelta), because -timedelta in isolation can overflow in cases
where date1 - timedelta does not. \code{\var{timedelta}.seconds}
and \code{\var{timedelta}.microseconds} are ignored.
\item[(3)]
This is exact, and cannot overflow. timedelta.seconds and
timedelta.microseconds are 0, and date2 + timedelta == date1
after.
\item[(4)]
In other words, \code{date1 < date2}
if and only if \code{\var{date1}.toordinal() <
\var{date2}.toordinal()}.
In order to stop comparison from falling back to the default
scheme of comparing object addresses, date comparison
normally raises \exception{TypeError} if the other comparand
isn't also a \class{date} object. However, \code{NotImplemented}
is returned instead if the other comparand has a
\method{timetuple} attribute. This hook gives other kinds of
date objects a chance at implementing mixed-type comparison.
If not, when a \class{date} object is
compared to an object of a different type, \exception{TypeError} is
raised unless the comparison is \code{==} or \code{!=}. The latter
cases return \constant{False} or \constant{True}, respectively.
\end{description}
Dates can be used as dictionary keys. In Boolean contexts, all
\class{date} objects are considered to be true.
Instance methods:
\begin{methoddesc}{replace}{year, month, day}
Return a date with the same value, except for those members given
new values by whichever keyword arguments are specified. For
example, if \code{d == date(2002, 12, 31)}, then
\code{d.replace(day=26) == date(2002, 12, 26)}.
\end{methoddesc}
\begin{methoddesc}{timetuple}{}
Return a \class{time.struct_time} such as returned by
\function{time.localtime()}. The hours, minutes and seconds are
0, and the DST flag is -1.
\code{\var{d}.timetuple()} is equivalent to
\code{time.struct_time((\var{d}.year, \var{d}.month, \var{d}.day,
0, 0, 0,
\var{d}.weekday(),
\var{d}.toordinal() - date(\var{d}.year, 1, 1).toordinal() + 1,
-1))}
\end{methoddesc}
\begin{methoddesc}{toordinal}{}
Return the proleptic Gregorian ordinal of the date, where January 1
of year 1 has ordinal 1. For any \class{date} object \var{d},
\code{date.fromordinal(\var{d}.toordinal()) == \var{d}}.
\end{methoddesc}
\begin{methoddesc}{weekday}{}
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}, a
Wednesday.
See also \method{isoweekday()}.
\end{methoddesc}
\begin{methoddesc}{isoweekday}{}
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}, a
Wednesday.
See also \method{weekday()}, \method{isocalendar()}.
\end{methoddesc}
\begin{methoddesc}{isocalendar}{}
Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
The ISO calendar is a widely used variant of the Gregorian calendar.
See \url{http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm}
for a good explanation.
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.
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, so that
\code{date(2003, 12, 29).isocalendar() == (2004, 1, 1)}
and
\code{date(2004, 1, 4).isocalendar() == (2004, 1, 7)}.
\end{methoddesc}
\begin{methoddesc}{isoformat}{}
Return a string representing the date in ISO 8601 format,
'YYYY-MM-DD'. For example,
\code{date(2002, 12, 4).isoformat() == '2002-12-04'}.
\end{methoddesc}
\begin{methoddesc}{__str__}{}
For a date \var{d}, \code{str(\var{d})} is equivalent to
\code{\var{d}.isoformat()}.
\end{methoddesc}
\begin{methoddesc}{ctime}{}
Return a string representing the date, for example
date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'.
\code{\var{d}.ctime()} is equivalent to
\code{time.ctime(time.mktime(\var{d}.timetuple()))}
on platforms where the native C \cfunction{ctime()} function
(which \function{time.ctime()} invokes, but which
\method{date.ctime()} does not invoke) conforms to the C standard.
\end{methoddesc}
\begin{methoddesc}{strftime}{format}
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 section~\ref{strftime-behavior} -- \method{strftime()} behavior.
\end{methoddesc}
\subsection{\class{datetime} Objects \label{datetime-datetime}}
A \class{datetime} object is a single object containing all the
information from a \class{date} object and a \class{time} object. Like a
\class{date} object, \class{datetime} assumes the current Gregorian
calendar extended in both directions; like a time object,
\class{datetime} assumes there are exactly 3600*24 seconds in every
day.
Constructor:
\begin{classdesc}{datetime}{year, month, day\optional{,
hour\optional{, minute\optional{,
second\optional{, microsecond\optional{,
tzinfo}}}}}}
The year, month and day arguments are required. \var{tzinfo} may
be \code{None}, or an instance of a \class{tzinfo} subclass. The
remaining arguments may be ints or longs, in the following ranges:
\begin{itemize}
\item \code{MINYEAR <= \var{year} <= MAXYEAR}
\item \code{1 <= \var{month} <= 12}
\item \code{1 <= \var{day} <= number of days in the given month and year}
\item \code{0 <= \var{hour} < 24}
\item \code{0 <= \var{minute} < 60}
\item \code{0 <= \var{second} < 60}
\item \code{0 <= \var{microsecond} < 1000000}
\end{itemize}
If an argument outside those ranges is given,
\exception{ValueError} is raised.
\end{classdesc}
Other constructors, all class methods:
\begin{methoddesc}{today}{}
Return the current local datetime, with \member{tzinfo} \code{None}.
This is equivalent to
\code{datetime.fromtimestamp(time.time())}.
See also \method{now()}, \method{fromtimestamp()}.
\end{methoddesc}
\begin{methoddesc}{now}{\optional{tz}}
Return the current local date and time. If optional argument
\var{tz} is \code{None} or not specified, this is like
\method{today()}, but, if possible, supplies more precision than can
be gotten from going through a \function{time.time()} timestamp (for
example, this may be possible on platforms supplying the C
\cfunction{gettimeofday()} function).
Else \var{tz} must be an instance of a class \class{tzinfo} subclass,
and the current date and time are converted to \var{tz}'s time
zone. In this case the result is equivalent to
\code{\var{tz}.fromutc(datetime.utcnow().replace(tzinfo=\var{tz}))}.
See also \method{today()}, \method{utcnow()}.
\end{methoddesc}
\begin{methoddesc}{utcnow}{}
Return the current UTC date and time, with \member{tzinfo} \code{None}.
This is like \method{now()}, but returns the current UTC date and time,
as a naive \class{datetime} object.
See also \method{now()}.
\end{methoddesc}
\begin{methoddesc}{fromtimestamp}{timestamp\optional{, tz}}
Return the local date and time corresponding to the \POSIX{}
timestamp, such as is returned by \function{time.time()}.
If optional argument \var{tz} is \code{None} or not specified, the
timestamp is converted to the platform's local date and time, and
the returned \class{datetime} object is naive.
Else \var{tz} must be an instance of a class \class{tzinfo} subclass,
and the timestamp is converted to \var{tz}'s time zone. In this case
the result is equivalent to
\code{\var{tz}.fromutc(datetime.utcfromtimestamp(\var{timestamp}).replace(tzinfo=\var{tz}))}.
\method{fromtimestamp()} may raise \exception{ValueError}, if the
timestamp is out of the range of values supported by the platform C
\cfunction{localtime()} or \cfunction{gmtime()} functions. 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
\method{fromtimestamp()}, and then it's possible to have two timestamps
differing by a second that yield identical \class{datetime} objects.
See also \method{utcfromtimestamp()}.
\end{methoddesc}
\begin{methoddesc}{utcfromtimestamp}{timestamp}
Return the UTC \class{datetime} corresponding to the \POSIX{}
timestamp, with \member{tzinfo} \code{None}.
This may raise \exception{ValueError}, if the
timestamp is out of the range of values supported by the platform
C \cfunction{gmtime()} function. It's common for this to be
restricted to years in 1970 through 2038.
See also \method{fromtimestamp()}.
\end{methoddesc}
\begin{methoddesc}{fromordinal}{ordinal}
Return the \class{datetime} corresponding to the proleptic
Gregorian ordinal, where January 1 of year 1 has ordinal 1.
\exception{ValueError} is raised unless \code{1 <= ordinal <=
datetime.max.toordinal()}. The hour, minute, second and
microsecond of the result are all 0,
and \member{tzinfo} is \code{None}.
\end{methoddesc}
\begin{methoddesc}{combine}{date, time}
Return a new \class{datetime} object whose date members are
equal to the given \class{date} object's, and whose time
and \member{tzinfo} members are equal to the given \class{time} object's.
For any \class{datetime} object \var{d}, \code{\var{d} ==
datetime.combine(\var{d}.date(), \var{d}.timetz())}. If date is a
\class{datetime} object, its time and \member{tzinfo} members are
ignored.
\end{methoddesc}
\begin{methoddesc}{strptime}{date_string, format}
Return a \class{datetime} corresponding to \var{date_string}, parsed
according to \var{format}. This is equivalent to
\code{datetime(*(time.strptime(date_string,
format)[0:6]))}. \exception{ValueError} is raised if the date_string and
format can't be parsed by \function{time.strptime()} or if it returns a
value which isn't a time tuple.
\versionadded{2.5}
\end{methoddesc}
Class attributes:
\begin{memberdesc}{min}
The earliest representable \class{datetime},
\code{datetime(MINYEAR, 1, 1, tzinfo=None)}.
\end{memberdesc}
\begin{memberdesc}{max}
The latest representable \class{datetime},
\code{datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)}.
\end{memberdesc}
\begin{memberdesc}{resolution}
The smallest possible difference between non-equal \class{datetime}
objects, \code{timedelta(microseconds=1)}.
\end{memberdesc}
Instance attributes (read-only):
\begin{memberdesc}{year}
Between \constant{MINYEAR} and \constant{MAXYEAR} inclusive.
\end{memberdesc}
\begin{memberdesc}{month}
Between 1 and 12 inclusive.
\end{memberdesc}
\begin{memberdesc}{day}
Between 1 and the number of days in the given month of the given
year.
\end{memberdesc}
\begin{memberdesc}{hour}
In \code{range(24)}.
\end{memberdesc}
\begin{memberdesc}{minute}
In \code{range(60)}.
\end{memberdesc}
\begin{memberdesc}{second}
In \code{range(60)}.
\end{memberdesc}
\begin{memberdesc}{microsecond}
In \code{range(1000000)}.
\end{memberdesc}
\begin{memberdesc}{tzinfo}
The object passed as the \var{tzinfo} argument to the
\class{datetime} constructor, or \code{None} if none was passed.
\end{memberdesc}
Supported operations:
\begin{tableii}{c|l}{code}{Operation}{Result}
\lineii{\var{datetime2} = \var{datetime1} + \var{timedelta}}{(1)}
\lineii{\var{datetime2} = \var{datetime1} - \var{timedelta}}{(2)}
\lineii{\var{timedelta} = \var{datetime1} - \var{datetime2}}{(3)}
\lineii{\var{datetime1} < \var{datetime2}}
{Compares \class{datetime} to \class{datetime}.
(4)}
\end{tableii}
\begin{description}
\item[(1)]
datetime2 is a duration of timedelta removed from datetime1, moving
forward in time if \code{\var{timedelta}.days} > 0, or backward if
\code{\var{timedelta}.days} < 0. The result has the same \member{tzinfo} member
as the input datetime, and datetime2 - datetime1 == timedelta after.
\exception{OverflowError} is raised if datetime2.year would be
smaller than \constant{MINYEAR} or larger than \constant{MAXYEAR}.
Note that no time zone adjustments are done even if the input is an
aware object.
\item[(2)]
Computes the datetime2 such that datetime2 + timedelta == datetime1.
As for addition, the result has the same \member{tzinfo} member
as the input datetime, and no time zone adjustments are done even
if the input is aware.
This isn't quite equivalent to datetime1 + (-timedelta), because
-timedelta in isolation can overflow in cases where
datetime1 - timedelta does not.
\item[(3)]
Subtraction of a \class{datetime} from a
\class{datetime} is defined only if both
operands are naive, or if both are aware. If one is aware and the
other is naive, \exception{TypeError} is raised.
If both are naive, or both are aware and have the same \member{tzinfo}
member, the \member{tzinfo} members are ignored, and the result is
a \class{timedelta} object \var{t} such that
\code{\var{datetime2} + \var{t} == \var{datetime1}}. No time zone
adjustments are done in this case.
If both are aware and have different \member{tzinfo} members,
\code{a-b} acts as if \var{a} and \var{b} were first converted to
naive UTC datetimes first. The result is
\code{(\var{a}.replace(tzinfo=None) - \var{a}.utcoffset()) -
(\var{b}.replace(tzinfo=None) - \var{b}.utcoffset())}
except that the implementation never overflows.
\item[(4)]
\var{datetime1} is considered less than \var{datetime2}
when \var{datetime1} precedes \var{datetime2} in time.
If one comparand is naive and
the other is aware, \exception{TypeError} is raised. If both
comparands are aware, and have the same \member{tzinfo} member,
the common \member{tzinfo} member is ignored and the base datetimes
are compared. If both comparands are aware and have different
\member{tzinfo} members, the comparands are first adjusted by
subtracting their UTC offsets (obtained from \code{self.utcoffset()}).
\note{In order to stop comparison from falling back to the default
scheme of comparing object addresses, datetime comparison
normally raises \exception{TypeError} if the other comparand
isn't also a \class{datetime} object. However,
\code{NotImplemented} is returned instead if the other comparand
has a \method{timetuple} attribute. This hook gives other
kinds of date objects a chance at implementing mixed-type
comparison. If not, when a \class{datetime} object is
compared to an object of a different type, \exception{TypeError}
is raised unless the comparison is \code{==} or \code{!=}. The
latter cases return \constant{False} or \constant{True},
respectively.}
\end{description}
\class{datetime} objects can be used as dictionary keys. In Boolean
contexts, all \class{datetime} objects are considered to be true.
Instance methods:
\begin{methoddesc}{date}{}
Return \class{date} object with same year, month and day.
\end{methoddesc}
\begin{methoddesc}{time}{}
Return \class{time} object with same hour, minute, second and microsecond.
\member{tzinfo} is \code{None}. See also method \method{timetz()}.
\end{methoddesc}
\begin{methoddesc}{timetz}{}
Return \class{time} object with same hour, minute, second, microsecond,
and tzinfo members. See also method \method{time()}.
\end{methoddesc}
\begin{methoddesc}{replace}{\optional{year\optional{, month\optional{,
day\optional{, hour\optional{, minute\optional{,
second\optional{, microsecond\optional{,
tzinfo}}}}}}}}}
Return a datetime with the same members, except for those members given
new values by whichever keyword arguments are specified. Note that
\code{tzinfo=None} can be specified to create a naive datetime from
an aware datetime with no conversion of date and time members.
\end{methoddesc}
\begin{methoddesc}{astimezone}{tz}
Return a \class{datetime} object with new \member{tzinfo} member
\var{tz}, adjusting the date and time members so the result is the
same UTC time as \var{self}, but in \var{tz}'s local time.
\var{tz} must be an instance of a \class{tzinfo} subclass, and its
\method{utcoffset()} and \method{dst()} methods must not return
\code{None}. \var{self} must be aware (\code{\var{self}.tzinfo} must
not be \code{None}, and \code{\var{self}.utcoffset()} must not return
\code{None}).
If \code{\var{self}.tzinfo} is \var{tz},
\code{\var{self}.astimezone(\var{tz})} is equal to \var{self}: no
adjustment of date or time members is performed.
Else the result is local time in time zone \var{tz}, representing the
same UTC time as \var{self}: after \code{\var{astz} =
\var{dt}.astimezone(\var{tz})},
\code{\var{astz} - \var{astz}.utcoffset()} will usually have the same
date and time members as \code{\var{dt} - \var{dt}.utcoffset()}.
The discussion of class \class{tzinfo} explains the cases at Daylight
Saving Time transition boundaries where this cannot be achieved (an issue
only if \var{tz} models both standard and daylight time).
If you merely want to attach a time zone object \var{tz} to a
datetime \var{dt} without adjustment of date and time members,
use \code{\var{dt}.replace(tzinfo=\var{tz})}. If
you merely want to remove the time zone object from an aware datetime
\var{dt} without conversion of date and time members, use
\code{\var{dt}.replace(tzinfo=None)}.
Note that the default \method{tzinfo.fromutc()} method can be overridden
in a \class{tzinfo} subclass to affect the result returned by
\method{astimezone()}. Ignoring error cases, \method{astimezone()}
acts like:
\begin{verbatim}
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)
\end{verbatim}
\end{methoddesc}
\begin{methoddesc}{utcoffset}{}
If \member{tzinfo} is \code{None}, returns \code{None}, else
returns \code{\var{self}.tzinfo.utcoffset(\var{self})}, and
raises an exception if the latter doesn't return \code{None}, or
a \class{timedelta} object representing a whole number of minutes
with magnitude less than one day.
\end{methoddesc}
\begin{methoddesc}{dst}{}
If \member{tzinfo} is \code{None}, returns \code{None}, else
returns \code{\var{self}.tzinfo.dst(\var{self})}, and
raises an exception if the latter doesn't return \code{None}, or
a \class{timedelta} object representing a whole number of minutes
with magnitude less than one day.
\end{methoddesc}
\begin{methoddesc}{tzname}{}
If \member{tzinfo} is \code{None}, returns \code{None}, else
returns \code{\var{self}.tzinfo.tzname(\var{self})},
raises an exception if the latter doesn't return \code{None} or
a string object,
\end{methoddesc}
\begin{methoddesc}{timetuple}{}
Return a \class{time.struct_time} such as returned by
\function{time.localtime()}.
\code{\var{d}.timetuple()} is equivalent to
\code{time.struct_time((\var{d}.year, \var{d}.month, \var{d}.day,
\var{d}.hour, \var{d}.minute, \var{d}.second,
\var{d}.weekday(),
\var{d}.toordinal() - date(\var{d}.year, 1, 1).toordinal() + 1,
dst))}
The \member{tm_isdst} flag of the result is set according to
the \method{dst()} method: \member{tzinfo} is \code{None} or
\method{dst()} returns \code{None},
\member{tm_isdst} is set to \code{-1}; else if \method{dst()} returns
a non-zero value, \member{tm_isdst} is set to \code{1};
else \code{tm_isdst} is set to \code{0}.
\end{methoddesc}
\begin{methoddesc}{utctimetuple}{}
If \class{datetime} instance \var{d} is naive, this is the same as
\code{\var{d}.timetuple()} except that \member{tm_isdst} is forced to 0
regardless of what \code{d.dst()} returns. DST is never in effect
for a UTC time.
If \var{d} is aware, \var{d} is normalized to UTC time, by subtracting
\code{\var{d}.utcoffset()}, and a \class{time.struct_time} for the
normalized time is returned. \member{tm_isdst} is forced to 0.
Note that the result's \member{tm_year} member may be
\constant{MINYEAR}-1 or \constant{MAXYEAR}+1, if \var{d}.year was
\code{MINYEAR} or \code{MAXYEAR} and UTC adjustment spills over a
year boundary.
\end{methoddesc}
\begin{methoddesc}{toordinal}{}
Return the proleptic Gregorian ordinal of the date. The same as
\code{self.date().toordinal()}.
\end{methoddesc}
\begin{methoddesc}{weekday}{}
Return the day of the week as an integer, where Monday is 0 and
Sunday is 6. The same as \code{self.date().weekday()}.
See also \method{isoweekday()}.
\end{methoddesc}
\begin{methoddesc}{isoweekday}{}
Return the day of the week as an integer, where Monday is 1 and
Sunday is 7. The same as \code{self.date().isoweekday()}.
See also \method{weekday()}, \method{isocalendar()}.
\end{methoddesc}
\begin{methoddesc}{isocalendar}{}
Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The
same as \code{self.date().isocalendar()}.
\end{methoddesc}
\begin{methoddesc}{isoformat}{\optional{sep}}
Return a string representing the date and time in ISO 8601 format,
YYYY-MM-DDTHH:MM:SS.mmmmmm
or, if \member{microsecond} is 0,
YYYY-MM-DDTHH:MM:SS
If \method{utcoffset()} does not return \code{None}, a 6-character
string is appended, giving the UTC offset in (signed) hours and
minutes:
YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM
or, if \member{microsecond} is 0
YYYY-MM-DDTHH:MM:SS+HH:MM
The optional argument \var{sep} (default \code{'T'}) is a
one-character separator, placed between the date and time portions
of the result. For example,
\begin{verbatim}
>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
... def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
\end{verbatim}
\end{methoddesc}
\begin{methoddesc}{__str__}{}
For a \class{datetime} instance \var{d}, \code{str(\var{d})} is
equivalent to \code{\var{d}.isoformat(' ')}.
\end{methoddesc}
\begin{methoddesc}{ctime}{}
Return a string representing the date and time, for example
\code{datetime(2002, 12, 4, 20, 30, 40).ctime() ==
'Wed Dec 4 20:30:40 2002'}.
\code{d.ctime()} is equivalent to
\code{time.ctime(time.mktime(d.timetuple()))} on platforms where
the native C \cfunction{ctime()} function (which
\function{time.ctime()} invokes, but which
\method{datetime.ctime()} does not invoke) conforms to the C
standard.
\end{methoddesc}
\begin{methoddesc}{strftime}{format}
Return a string representing the date and time, controlled by an
explicit format string. See section~\ref{strftime-behavior} --
\method{strftime()} behavior.
\end{methoddesc}
\subsection{\class{time} Objects \label{datetime-time}}
A time object represents a (local) time of day, independent of any
particular day, and subject to adjustment via a \class{tzinfo} object.
\begin{classdesc}{time}{hour\optional{, minute\optional{, second\optional{,
microsecond\optional{, tzinfo}}}}}
All arguments are optional. \var{tzinfo} may be \code{None}, or
an instance of a \class{tzinfo} subclass. The remaining arguments
may be ints or longs, in the following ranges:
\begin{itemize}
\item \code{0 <= \var{hour} < 24}
\item \code{0 <= \var{minute} < 60}
\item \code{0 <= \var{second} < 60}
\item \code{0 <= \var{microsecond} < 1000000}.
\end{itemize}
If an argument outside those ranges is given,
\exception{ValueError} is raised. All default to \code{0} except
\var{tzinfo}, which defaults to \constant{None}.
\end{classdesc}