Learn python with socratica [My notes] - part 8- Datetiems Module

Lesson 10

Datetime是一个很实用的模块,通常在我们写程序的时候,一般会用到系统时间来计算模型的效果,或者记录模型训练的过程。本节详细介绍python的这个模块。

1
2
3
4
# first thing: import module
import datetime
# Let's look at its dir
dir(datetime)
['MAXYEAR',
 'MINYEAR',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'date',
 'datetime',
 'datetime_CAPI',
 'time',
 'timedelta',
 'timezone',
 'tzinfo']

我们可以看到,其中有date,time,datetime三个子方法。其中,date是关于日期的,time是关于时间的,而datetime是两者的结合。

1
help(datetime.date)
Help on class date in module datetime:

class date(builtins.object)
 |  date(year, month, day) --> date object
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(...)
 |      Formats self with strftime.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __radd__(self, value, /)
 |      Return value+self.
 |  
 |  __reduce__(...)
 |      __reduce__() -> (cls, state)
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  ctime(...)
 |      Return ctime() style string.
 |  
 |  fromordinal(...) from builtins.type
 |      int -> date corresponding to a proleptic Gregorian ordinal.
 |  
 |  fromtimestamp(...) from builtins.type
 |      timestamp -> local date from a POSIX timestamp (like time.time()).
 |  
 |  isocalendar(...)
 |      Return a 3-tuple containing ISO year, week number, and weekday.
 |  
 |  isoformat(...)
 |      Return string in ISO 8601 format, YYYY-MM-DD.
 |  
 |  isoweekday(...)
 |      Return the day of the week represented by the date.
 |      Monday == 1 ... Sunday == 7
 |  
 |  replace(...)
 |      Return date with new specified fields.
 |  
 |  strftime(...)
 |      format -> strftime() style string.
 |  
 |  timetuple(...)
 |      Return time tuple, compatible with time.localtime().
 |  
 |  today(...) from builtins.type
 |      Current date or datetime:  same as self.__class__.fromtimestamp(time.time()).
 |  
 |  toordinal(...)
 |      Return proleptic Gregorian ordinal.  January 1 of year 1 is day 1.
 |  
 |  weekday(...)
 |      Return the day of the week represented by the date.
 |      Monday == 0 ... Sunday == 6
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  day
 |  
 |  month
 |  
 |  year
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  max = datetime.date(9999, 12, 31)
 |  
 |  min = datetime.date(1, 1, 1)
 |  
 |  resolution = datetime.timedelta(1)

从文档中可以看出,datetime.date已经包含了从(1,1,1)到(9999,12,31)所有的日期,并且也给出了如何创建一个日期的方式。

1
2
3
4
5
6
7
gvr = datetime.date(1956,1,31)
# This is the birthday of Guido van Rossum, the creator of python
print(gvr) # you will see the date you built
# And you can print date's year, month and day respectively
print(gvr.year)
print(gvr.month)
print(gvr.day)
1956-01-31
1956
1
31

datetime中还有一个模块timedelta,用来表示天数的。

1
2
3
mill = datetime.date(2000,1,1)
dt = datetime.timedelta(100)
print(mill + dt)
2000-04-10

python中对date有默认的格式:yyyy-mm-dd。如果想要得到自己的日期格式,就需要date提供的指令自由组合。参见:https://docs.python.org/3/library/datetime.html,文档中有详细解释。

1
2
# Day-name, Month-name, Day-#, Year
print(gvr.strftime("%A,%B,%d,%Y"))
Tuesday,January,31,1956

你会发现,时间直接以字符串的形式给出,那么也就意味着将时间加到指定的字符串中是可行的,这就很方便了。

1
2
message = "GVR was born on {:%A,%B,%d,%Y}"
print(message.format(gvr))
GVR was born on Tuesday,January,31,1956

是不是很酷?下面我们做一个更酷的事情
记录事件:SpaceX公司在UTC时区2017年3月30日22:27完成重用了第一级火箭。

1
2
3
4
5
6
7
import datetime
launch_date = datetime.date(2017,3,10)
launch_time = datetime.time(22,27,0)
launch_datetime = datetime.datetime(2017,3,10,22,27,0)
print(launch_date)
print(launch_time)
print(launch_datetime)
2017-03-10
22:27:00
2017-03-10 22:27:00
1
2
3
4
# you can also get the hour/minute/second
print(launch_time.hour)
print(launch_time.minute)
print(launch_time.second)
22
27
0

同理,你也可以用datetime获取所有的信息。下面介绍如何得到当前时间。

1
2
3
# Access current datetime
now = datetime.datetime.today()
print(now)
2018-11-02 01:26:00.741418

741418是微秒—microsecond。

1
print(now.microsecond)
741418
1
2
3
4
5
# convert string to datetime
moon_loading = "7/20/1969"
# use strptime() function
moon_loading_datetime = datetime.datetime.strptime(moon_loading,"%m/%d/%Y")
print(moon_loading_datetime)
1969-07-20 00:00:00

此时moon_loading的字符串已经转换成datetime的对象。

1
print(type(moon_loading_datetime))
<class 'datetime.datetime'>

Youtube source:
https://www.youtube.com/watch?v=bY6m6_IIN94&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-