Python Datetime Reference

Python Datetime Reference

Import

from datetime import datetime

Creating datetime object

# for current date & time
dt = datetime.now()
dt = datetime.utcnow()

# from given date & time
dt = datetime(2008, 11, 10, 17, 53, 59) # 2008-11-10 17:53:59

# from given string containing date & time
date_str = "2008-11-10 17:53:59"
dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")

# from given timestamp (seconds since 1970-01-01 00:00 UTC)
timestamp = 1226527167
dt = datetime.fromtimestamp(timestamp)
dt = datetime.utcfromtimestamp(timestamp)

Using datetime object

# to string
str = dt.strftime("%Y-%m-%d %H:%M:%S")

# to timestamp (seconds since epoch 01.01.1970 00:00:00)
timestamp = dt.timestamp()

# current date & time to timestamp without having to create a datetime object
timestamp = datetime.now().timestamp()
timestamp = datetime.utcnow().timestamp()

Datetime attributes

  • dt.year
  • dt.month
  • dt.day
  • dt.hour
  • dt.minute
  • dt.second
  • dt.microsecond
  • dt.tzinfo
  • dt.tzname()
  • dt.weekday() # 0 = Monday, 6 = Sunday

Datetime string format

Day of week

  • %a - Weekday abbreviated (eg: Sun)
  • %A - Weekday full name (eg: Sunday)
  • %w - Weekday number (0=Sunday 6=Saturday)

Day of month

  • %d - Day of month (zero padded eg: 02)

Months

  • %b - Month name abbreviated (eg: Jan)
  • %B - Month full name (eg: January)
  • %m - Month number (zero padded eg: 01)

Years

  • %y - Year without century (zero padded)
  • %Y - Year with century (zero padded)

Hours

  • %H - Hour 24 hour clock (zero padded)
  • %I - Hour 12 hour clock (zero padded)
  • %p - AM or PM

Minutes

  • %M - Minute (zero padded)

Seconds

  • %S - Second (zero padded)

Timezones

  • %z - Timezont UTC offset (eg: +0100)
  • %Z - Timezone name

Reference