File tree Expand file tree Collapse file tree 4 files changed +73
-0
lines changed
Expand file tree Collapse file tree 4 files changed +73
-0
lines changed Original file line number Diff line number Diff line change 1+ # How to Get and Use the Current Time in Python
2+
3+ The code samples and supporting materials for the [ corresponding tutorial] ( https://realpython.com/python-get-current-time/ ) on Real Python.
Original file line number Diff line number Diff line change 1+ from datetime import datetime
2+ import time
3+
4+
5+ datetime_unixtime = datetime .now ().timestamp ()
6+ time_unixtime = time .time ()
7+ timezone_aware_unixtime = datetime .now ().astimezone ().timestamp ()
8+
9+ print (
10+ f"""
11+ { datetime_unixtime = }
12+ { time_unixtime = }
13+ { timezone_aware_unixtime = }
14+ """
15+ )
Original file line number Diff line number Diff line change 1+ from datetime import datetime , timezone
2+
3+ """
4+ datetime.datetime.now() is preferred over:
5+
6+ - datetime.utc.now()
7+ - datetime.today()
8+ - time.time()
9+ """
10+
11+ now = datetime .now ()
12+
13+ print (
14+ f"""
15+ { now = }
16+ { now .time () = }
17+ { now .day = }
18+ { now .hour = }
19+ { now .minute = }
20+ { now .isoformat () = }
21+ { now .weekday () = }
22+ { now .isoweekday () = }
23+ { now .isocalendar () = }
24+
25+ """
26+ )
27+
28+ # https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
29+ print (now .strftime ("%A, %B %d %Z" ))
30+
31+
32+ # UTC timezone aware object
33+
34+ now = datetime .now (timezone .utc )
35+
36+ print (
37+ f"""
38+ UTC timezone aware:
39+ { now = }
40+ { now .isoformat () = }
41+ """
42+ )
43+
44+ print (now .strftime ("%A, %B %d %Z" ))
Original file line number Diff line number Diff line change 1+ import time
2+
3+
4+ print (
5+ f"""
6+ { time .time () = }
7+ { time .ctime () = }
8+ { time .gmtime () = }
9+ { time .localtime () = }
10+ """
11+ )
You can’t perform that action at this time.
0 commit comments