Create Time: 11th May 2024
Title: "[[Datetime]]"
status: DONE
Author:
- Dr. Eric Zhao
tags:
- Python
- NOTE
created: 2024-05-11T13:40
updated: 2024-06-11T01:16
With thanks to Dr. Eric Zhao from the Finance Mathematics Program, BNU-HKBU United International College
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
objectimport 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
['__add__',
'__class__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__ne__',
'__new__',
'__radd__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rsub__',
'__setattr__',
'__sizeof__',
'__str__',
'__sub__',
'__subclasshook__',
'astimezone',
'combine',
'ctime',
'date',
'day',
'dst',
'fold',
'fromisocalendar',
'fromisoformat',
'fromordinal',
'fromtimestamp',
'hour',
'isocalendar',
'isoformat',
'isoweekday',
'max',
'microsecond',
'min',
'minute',
'month',
'now',
'replace',
'resolution',
'second',
'strftime',
'strptime',
'time',
'timestamp',
'timetuple',
'timetz',
'today',
'toordinal',
'tzinfo',
'tzname',
'utcfromtimestamp',
'utcnow',
'utcoffset',
'utctimetuple',
'weekday',
'year']
dt = datetime.datetime(2003, 8, 4, 12, 30, 45)
print (time.time())
dt = datetime.datetime.fromtimestamp(time.time())
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)
import datetime
print ('construct object from y-m-d, h-m-s-m attributes')
dt = datetime.datetime(2003, 8, 4, 12, 30, 45)
for attr in [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']:
print(attr, ':', getattr(dt, attr))
construct object from y-m-d, h-m-s-m attributes
year : 2003
month : 8
day : 4
hour : 12
minute : 30
second : 45
microsecond : 0
import time
time.time?
time.time()
1713166214.4785035
time.time()/(3600*24*365.25)
54.286961444911746
print ('build object from current system time in ticks')
print (time.time())
dt = datetime.datetime.fromtimestamp(time.time())
for attr in [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']:
print (attr, ':', getattr(dt, attr))
build object from current system time in ticks
1713166214.5121484
year : 2024
month : 4
day : 15
hour : 15
minute : 30
second : 14
microsecond : 512215
import datetime
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)
print ('now we successfully obtain the datetime object')
for attr in [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']:
print (attr, ':', getattr(dt, attr))
another_form = '%Y-%m-%d %H-%M-%S'
print ('express the date-time in a new form:')
# transform the datetime object to date string
dt_new_format = dt.strftime(another_form)
print (dt_new_format)
original time is: 2017-08-02 18:14:26, time format is: %Y-%m-%d %H:%M:%S
now we successfully obtain the datetime object
year : 2017
month : 8
day : 2
hour : 18
minute : 14
second : 26
microsecond : 0
express the date-time in a new form:
2017-08-02 18-14-26
date
objectimport 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
time
objectimport 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
date
and time
objectimport 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
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
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 2days('1980-08-28', '1980-08-30')
should return 3days('1980-08-26', '1980-08-30')
should return 5days('1980-08-29', '1980-08-29')
should return 1days('1980-08-30', '1980-08-29')
should return 0You 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!