Skip to content
Search

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:

d1 = 16/09/2019
d2 = September 16, 2019
d3 = 09/16/19
d4 = Sep-16-2019

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

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

Favorite site

References


  1. SystemSection-Python-datetime.pdf ↩

author Zer0 sitemap