Python:datetime
lastmod 2021-12-03created 2015-03-249 edits
Current time in milliseconds
from datetime import datetime
from datetime import timedelta
start_time = datetime.now()
# returns the elapsed milliseconds since the start of the program
def millis():
dt = datetime.now() - start_time
ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
return ms
Current date in different formats
from datetime import date
today = date.today()
# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print("d1 =", d1)
# Textual month, day and year
d2 = today.strftime("%B %d, %Y")
print("d2 =", d2)
# mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)
# Month abbreviation, day and year
d4 = today.strftime("%b-%d-%Y")
print("d4 =", d4)<Paste>
When you run the program, the output will be something like:
Get current date and time
from datetime import datetime
# datetime object containing current date and time
now = datetime.now()
print("now =", now)
# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
naive datetime vs aware datetime
- [Recommended] Learning about time zones in Python (datetime.timezone)
The differences are as follows:
- Naive datetime
- Does not by itself contain enough information to determine its time zone.
- e.g.
datetime.datetime(2019, 2, 15, 4, 58, 4, 114979)
- Aware Datetime (timezone-aware)
- Includes a time zone (Timezone).
- e.g.
datetime.datetime(2019, 2, 15, 4, 58, 4, 114979, tzinfo=UTC)
tzinfo holds the offset of local time from UTC, the time zone name, and how to represent the DST offset.
Since a naive datetime is ambiguous about which time zone it is based on, using an aware datetime is recommended.
See also
- Python
- Python:datetime
- Python:time
- python-dateutil (dateutil) - powerful extensions to datetime
Favorite site
References
-
SystemSection-Python-datetime.pdf ↩