Datetime

With thanks to Dr. Eric Zhao from the Finance Mathematics Program, BNU-HKBU United International College

Content

  • Create datetime object for time parsing, formatting, and arithmetic.

The resources come from here.

  • The datetime module provides a number of ways to deal with dates, times, and time intervals.

  • The datetime module contains the following types:

    • datetime type: represents a date and a time during that day.
    • date type: represents just a date, between year 1 and 9999 (see below for more about the calendar used by the datetime module)
    • time type: represents a time, independent of the datetime.date
    • timedelta type: represents the difference between two time or date objects.

The datetime Type

  • objects of the datetime type represent a date and a time in some timezone, which has 7 attributes 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond' as a tuple.
  • You can construct the datetime.datetime object by the tuple, or retrive the tuple by datetime.datetime object.

The datetime object

import datetime
d = datetime.datetime.now()
print (d.year)
print (d.month)
print (d.day)
print (d.hour)
print (d.minute)
print (d.second)
print (d.microsecond)
2024
4
15
15
30
14
378257

Construct datetime object

  1. By 7-elements tuple
dt = datetime.datetime(2003, 8, 4, 12, 30, 45)
  1. From current system time in ticks
print (time.time())
dt = datetime.datetime.fromtimestamp(time.time())
  1. From time string
str_time = '2017-08-02 18:14:26'
form = '%Y-%m-%d %H:%M:%S'
print ('original time is: %s, time format is: %s'%(str_time, form))
# transform the date string to datetime object
dt = datetime.datetime.strptime(str_time, form) 

The date-Types

2.1 date object

  • The date type represents the date portions of a datetime object. It has attributes for year, month, and day.
import datetime

# build "date" object by year-month-day triple
d = datetime.date(2017, 8, 2)
print ('year: %d, month: %d, day: %d'% (d.year, d.month, d.day))
print (d.strftime('%Y-%m-%d'))
year: 2017, month: 8, day: 2
2017-08-02

2.2 time object

import datetime

t = datetime.time(18, 54, 32)
print (t)
print (t.hour, t.minute, t.second, t.microsecond)
18:54:32
18 54 32 0

2.3 Combine date and time object

  • The datetime type provides method to extract date and time objects, as well as a class method that combines two objects into a single datetime object:
import datetime
# generate a datetime.datetime object
dt = datetime.datetime.now()
date = dt.date()
print (type(date))
time = dt.time()
print (type(time))
dt1 = datetime.datetime.combine(date, time)
print (dt == dt1)
<class 'datetime.date'>
<class 'datetime.time'>
True
day = datetime.date(2017, 8, 2)
time = datetime.time(18, 54, 32)
dt = datetime.datetime.combine(day, time)
print (dt.strftime('%Y-%m-%d %H-%M-%S'))
2017-08-02 18-54-32

3. Date Arithmetic

3.1 datetime arithmetic

  • In somecases, you may need to add/minus a period of time on a datetime. For example, if you are asked to add 5 days, 7 hours, 36 minutes, 10 microseconds to the datetime "2017-08-02 17:29:12:34", what is the result?
  • The datetime.timedelta object will help you perform such operation.
import datetime
# you can build a datetime.timedelta object (set up a period 
# of time) by 7-elements tuple.
print ("microseconds:", datetime.timedelta(microseconds=1))
print ("milliseconds:", datetime.timedelta(milliseconds=1))
print ("seconds     :", datetime.timedelta(seconds=1))
print ("minutes     :", datetime.timedelta(minutes=1))
print ("hours       :", datetime.timedelta(hours=1))
print ("days        :", datetime.timedelta(days=1))
print ("weeks       :", datetime.timedelta(weeks=1))
microseconds: 0:00:00.000001
milliseconds: 0:00:00.001000
seconds     : 0:00:01
minutes     : 0:01:00
hours       : 1:00:00
days        : 1 day, 0:00:00
weeks       : 7 days, 0:00:00
# this example will solve the above datetime arithmetic problem
import datetime

dt = datetime.datetime(2017,8,2,17,29,12,34)
print ('original time: ', dt)
# we use td to represent the period of time we want to add
td = datetime.timedelta(weeks=0, days=5, hours=7, minutes=36, microseconds=10)
# this will be td time later w.r.t the original time dt
datetime_future = dt + td
# this will be td time earlier w.r.t the original time dt
datetime_past = dt - td
print ('after adding some time: ', datetime_future)
print ('after minus some time: ', datetime_past)
original time:  2017-08-02 17:29:12.000034
after adding some time:  2017-08-08 01:05:12.000044
after minus some time:  2017-07-28 09:53:12.000024

3.2 Comparing datetimes

  • Both date and time values can be compared using the standard operators to determine which is earlier or later.
import datetime

print ('Times:')
t1 = datetime.time(12, 55, 0)
print ('\tt1:', t1)
t2 = datetime.time(13, 5, 0)
print ('\tt2:', t2)
print ('\tt1 < t2:', t1 < t2)

print ('Dates:')
d1 = datetime.date.today()
print ('\td1:', d1)
d2 = datetime.date.today() + datetime.timedelta(days=1)
print ('\td2:', d2)
print ('\td1 > d2:', d1 > d2)
Times:
 t1: 12:55:00
 t2: 13:05:00
 t1 < t2: True
Dates:
 d1: 2024-04-15
 d2: 2024-04-16
 d1 > d2: False

Task 1: Complete the function last_week which accepts a string s representing a date and returns another string representing its previous week. Note that the format of s is mm/dd/yyyy and the returned string of the funtion should use the same format, too. You can assume that the input is always valid.

Hint: the methods you may need in this question are: strptime(), timedelta(), strftime().

import datetime
def last_week(s):
    # YOUR CODE HERE
    form = '%m/%d/%Y'
    d1=datetime.datetime.strptime(s, form) 
    d2 = d1-datetime.timedelta(weeks=1)
    d2 = d2.strftime(form)
    return d2

assert last_week('01/01/2024') == '12/25/2023'
assert last_week('03/07/2020') == '02/29/2020'
# This cell contains hidden tests, do NOT delete!
# This cell contains hidden tests, do NOT delete!

Task 2: Complete the function days which accepts two strings, start and end, representing two dates for format yyyy-mm-dd. It returns the number of days between the start date and the end date, both end inclusive. Note that days should return 0 if the start date is later than the end date.

For example,

  • days('1980-08-28', '1980-08-29') should return 2
  • days('1980-08-28', '1980-08-30') should return 3
  • days('1980-08-26', '1980-08-30') should return 5
  • days('1980-08-29', '1980-08-29') should return 1
  • days('1980-08-30', '1980-08-29') should return 0

You can assume that the input is always valid.

import datetime
def days(start, end):
    # YOUR CODE HERE
    form = '%Y-%m-%d'
    start_date=datetime.datetime.strptime(start, form) 
    end_date=datetime.datetime.strptime(end, form) 
#     print(start_date,end_date)
    if(start_date>end_date):
        return 0
    else:
        delta = end_date - start_date
        return delta.days + 1  # 包含结束日期,如果只需要差距可以去掉 +1
#     raise NotImplementedError()
# print(days('1980-08-28', '1980-08-29'))
assert days('1980-08-28', '1980-08-29') == 2
assert days('1980-08-28', '1980-08-30') == 3
assert days('1980-08-26', '1980-08-30') == 5
assert days('1980-08-29', '1980-08-29') == 1
assert days('1980-08-30', '1980-08-29') == 0
# This cell contains hidden tests, do NOT delete!
# This cell contains hidden tests, do NOT delete!
# This cell contains hidden tests, do NOT delete!
# This cell contains hidden tests, do NOT delete!