12/20/2017

For record only

1.import module 和 from module import * 区别:

导入模块,对于模块中的函数,每次调用需要模块.类.函数 来使用

from xx import fun 直接导入模块中的函数,直接fun() 就可以使用

from xx import * 所有模块中函数可以直接使用

Example:

import datetime
datetime.strptime("20170913", "%Y%m%d").date()
AttributeError: module 'datetime' has no attribute 'strptime'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-43-32a94c8a2510> in <module>()
----> 1 datetime.strptime("20170913", "%Y%m%d").date()
AttributeError: module 'datetime' has no attribute 'strptime'

Error, because there is a datetime class inside the datetime module(same name). The strptime() method is in the datetime class.

datetime.datetime.strptime("20170913", "%Y%m%d").date()
datetime.date(2017, 9, 13)

no error

OR

from datetime import *
datetime.strptime("20170913", "%Y%m%d").date()
datetime.date(2017, 9, 13)

All the methods can be used now

2. datetime.datetime.strftime() 用法

将很多形式的表示日期的字符串 转换成 datetime的标准日期格式:

%a Abbreviated weekday name

%A Full weekday name

%b Abbreviated month name

%B Full month name

%c Date and time representation appropriate for locale

%d Day of month as decimal number (01 – 31)

%H Hour in 24-hour format (00 – 23)

%I Hour in 12-hour format (01 – 12)

%j Day of year as decimal number (001 – 366)

%m Month as decimal number (01 – 12)

%M Minute as decimal number (00 – 59)

%p Current locale’s A.M./P.M. indicator for 12-hour clock

%S Second as decimal number (00 – 59)

%U Week of year as decimal number, with Sunday as first day of week (00 – 51)

%w Weekday as decimal number (0 – 6; Sunday is 0)

%W Week of year as decimal number, with Monday as first day of week (00 – 51)

%x Date representation for current locale

%X Time representation for current locale

%y Year without century, as decimal number (00 – 99)

%Y Year with century, as decimal number

%z, %Z Time-zone name or abbreviation; no characters if time zone is unknown

%% Percent sign

Example:

datetime.strptime("2017-09-12", "%Y-%m-%d").date()
datetime.date(2017, 9, 12)
datetime.strptime('Sep-21-09 16:34','%b-%d-%y %H:%M')
datetime.datetime(2009, 9, 21, 16, 34)

class datetime.date 可以相减,得到class datetime.timedelta

Example

a = datetime.strptime("2017-09-12", "%Y-%m-%d").date()
b = datetime.strptime("2017-09-13", "%Y-%m-%d").date()
a - b
# Out put
datetime.timedelta(-1)

然后可以通过.days拿到这个number

c = a - b
c.days
-1

3. 字典对象的Pythonic 用法:

字典对象的 Pythonic 用法

Highlight:

1. 使用 setdefault() 初始化字典键值 – 动态更新字典

3. 使用 iteritems() 迭代大数据

    原文作者:Rhino
    原文地址: https://zhuanlan.zhihu.com/p/32207934
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞