Use datetime module to create datetime and do calculation

Creating a New Date


import datetime# from w  w w .  j  a v a  2 s . com
print datetime.datetime.today()

d = datetime.datetime(2007,01,01)
print d

The code above generates the following result.

Create a datetime from year, month, day, hour, minute second.


from datetime import datetime
d = datetime(datetime.now().year, datetime.now().month, datetime.now().day,11, 59, 0 )
print d

The code above generates the following result.

Format a datetime value


from datetime import date
now = date.today()#   ww  w.  ja  v  a  2  s. c o  m
print now

print now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")

The code above generates the following result.

Calendar arithmetic


from datetime import date
# from   w ww .  ja  v  a2 s  .  c  o m

birthday = date(1964, 7, 31)
now = date(2006, 7, 31)

age = now - birthday
print age.days

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules