Skip to content

Python:datetime

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

각각의 차이는 다음과 같다:

Naive datetime
그 자체 만으로 시간대를 찾을 수 있는 충분한 정보를 포함하지 않습니다.
e.g. datetime.datetime(2019, 2, 15, 4, 58, 4, 114979)
Aware Datetime (timezone-aware)
시간대 (Timezone)를 포함.
e.g. datetime.datetime(2019, 2, 15, 4, 58, 4, 114979, tzinfo=UTC)

tzinfo는 UTC, 시간대 이름 및 DST 오프셋에서 로컬 시간의 오프셋을 나타내는 방법을 담고 있습니다.

naive datetime은 어느 시간대를 기준으로 하는 시각인지 모호하므로 aware datetime을 이용하는 것을 권장합니다.

See also

Favorite site

References


  1. SystemSection-Python-datetime.pdf