第三方库 --datetime库

 f==format     p==parse

1、获取当前时间(日期格式)

from datetime import datetime
datetime.now()
#输出  datetime.datetime(2019, 9, 12, 20, 17, 15, 426867)

2、由日期格式转化为字符串格式的函数为: datetime.datetime.strftime()

datetime.now().strftime('%b-%m-%y %H:%M:%S')
#输出'Sep-09-19 20:12:56'

3、由字符串格式转化为日期格式的函数为: datetime.datetime.strptime()

datetime.strptime('Sep-09-19 20:12:56','%b-%d-%y %H:%M:%S')
#输出为:    datetime.datetime(2019, 9, 9, 20, 12, 56)

4、两个函数都涉及日期时间的格式化字符串,列举如下:

%a 星期几的简写;如 星期三为Web 
%A 星期几的全称;如 星期三为Wednesday 
%b 月份的简写; 如4月份为Apr 
%B 月份的全称; 如4月份为April 
%c 标准的日期的时间串;(如: 04/07/10 10:43:39) 
%C 年份的后两位数字 
%d 十进制表示的每月的第几天 
%D 月/天/年 
%e 在两字符域中,十进制表示的每月的第几天 
%F 年-月-日 
%g 年份的后两位数字,使用基于周的年 
%G 年分,使用基于周的年 
%h 简写的月份名 
%H 24小时制的小时 
%I 12小时制的小时 
%j 十进制表示的每年的第几天 
%m 十进制表示的月份 
%M 十时制表示的分钟数 
%n 新行符 
%p 本地的AM或PM的等价显示 
%r 12小时的时间 
%R 显示小时和分钟:hh:mm 
%S 十进制的秒数 
%t 水平制表符 
%T 显示时分秒:hh:mm:ss 
%u 每周的第几天,星期一为第一天 (值从0到6,星期一为0) 
%U 第年的第几周,把星期日做为第一天(值从0到53) 
%V 每年的第几周,使用基于周的年 
%w 十进制表示的星期几(值从0到6,星期天为0) 
%W 每年的第几周,把星期一做为第一天(值从0到53) 
%x 标准的日期串 
%X 标准的时间串 
%y 不带世纪的十进制年份(值从0到99) 
%Y 带世纪部分的十制年份 
%z,%Z 时区名称,如果不能得到时区名称则返回空字符。 
%% 百分号

 

import datetime

import time

1、string格式转换成datetime格式

string = '2019-09-12'

date_time = datetime.datetime.strptime(string,'%Y-%m-%d')

 

2、datetime格式转换成String格式

string = date_time.strftime('%Y-%m-%d')

 

3、datetime转换为时间戳

time_stamp = time.mktime(date_time.timetuple())

 

4、时间戳转换成string

string = time.strftime('%Y-%m-%d',time.localtime(time_stamp))

 

一个timedelta对象表示一个时间长度,两个日期或者时间的差值
class datetime.timedelta(days=0,seconds=0,microseconds=0,milliseconds=0,minutes=0,hours=0,weeks=0)
所有的参数都是可选的,默认值为0,参数可以是整数或者浮点数,既可以是整数也可以是负数。
虽然说参数可以传递的单位很多,但是python内部实现只存储了days,seconds和microseconds三种单位,所有其他的单位在计算时都会转换成相应的三种单位:
1 millisecond = 1000 microseconds
1 minute = 60 seconds
1 hour = 3600 seconds
1 week = 7 days
一、两个datetime.datetime类型相减或者两个datetime.date类型相减的结果就是daftetime.delta类型
二、以下是具体使用方法
1、以下是打印未来一天后的时间

def next_day(date_str):
    date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
    date = date + datetime.timedelta(days=1)
    return date.strftime("%Y-%m-%d")

 

2、以下是打印一天前的时间

def prev_day(date_str):
    date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
    date = date - datetime.timedelta(days=1)
    return date.strftime("%Y-%m-%d")

 

同理,其他时间单位也是一样的

 

以下是原文说明

CLASSES

    builtins.object

        date

            datetime

        time

        timedelta

        tzinfo

            timezone

   

    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.

     | 

     |  __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.

     | 

     |  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().

     | 

     |  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

     | 

     |  ----------------------------------------------------------------------

     |  Class methods defined here:

     | 

     |  fromisocalendar(...) from builtins.type

     |      int, int, int -> Construct a date from the ISO year, week number and weekday.

     |     

     |      This is the inverse of the date.isocalendar() function

     | 

     |  fromisoformat(...) from builtins.type

     |      str -> Construct a date from the output of date.isoformat()

     | 

     |  fromordinal(...) from builtins.type

     |      int -> date corresponding to a proleptic Gregorian ordinal.

     | 

     |  fromtimestamp(timestamp, /) from builtins.type

     |      Create a date from a POSIX timestamp.

     |     

     |      The timestamp is a number, e.g. created via time.time(), that is interpreted

     |      as local time.

     | 

     |  today(...) from builtins.type

     |      Current date or datetime:  same as self.__class__.fromtimestamp(time.time()).

     | 

     |  ----------------------------------------------------------------------

     |  Static methods defined here:

     | 

     |  __new__(*args, **kwargs) from builtins.type

     |      Create and return a new object.  See help(type) for accurate signature.

     | 

     |  ----------------------------------------------------------------------

     |  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(days=1)

   

    class datetime(date)

     |  datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

     | 

     |  The year, month and day arguments are required. tzinfo may be None, or an

     |  instance of a tzinfo subclass. The remaining arguments may be ints.

     | 

     |  Method resolution order:

     |      datetime

     |      date

     |      builtins.object

     | 

     |  Methods defined here:

     | 

     |  __add__(self, value, /)

     |      Return self+value.

     | 

     |  __eq__(self, value, /)

     |      Return self==value.

     | 

     |  __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.

     | 

     |  __radd__(self, value, /)

     |      Return value+self.

     | 

     |  __reduce__(...)

     |      __reduce__() -> (cls, state)

     | 

     |  __reduce_ex__(...)

     |      __reduce_ex__(proto) -> (cls, state)

     | 

     |  __repr__(self, /)

     |      Return repr(self).

     | 

     |  __rsub__(self, value, /)

     |      Return value-self.

     | 

     |  __str__(self, /)

     |      Return str(self).

     | 

     |  __sub__(self, value, /)

     |      Return self-value.

     | 

     |  astimezone(...)

     |      tz -> convert to local time in new timezone tz

     | 

     |  ctime(...)

     |      Return ctime() style string.

     | 

     |  date(...)

     |      Return date object with same year, month and day.

     | 

     |  dst(...)

     |      Return self.tzinfo.dst(self).

     | 

     |  isoformat(...)

     |      [sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].

     |      sep is used to separate the year from the time, and defaults to 'T'.

     |      timespec specifies what components of the time to include (allowed values are 'auto', 'hours', 'minutes', 'seconds', 'milliseconds', and 'microseconds').

     | 

     |  replace(...)

     |      Return datetime with new specified fields.

     | 

     |  time(...)

     |      Return time object with same time but with tzinfo=None.

     | 

     |  timestamp(...)

     |      Return POSIX timestamp as float.

     | 

     |  timetuple(...)

     |      Return time tuple, compatible with time.localtime().

     | 

     |  timetz(...)

     |      Return time object with same time and tzinfo.

     | 

     |  tzname(...)

     |      Return self.tzinfo.tzname(self).

     | 

     |  utcoffset(...)

     |      Return self.tzinfo.utcoffset(self).

     | 

     |  utctimetuple(...)

     |      Return UTC time tuple, compatible with time.localtime().

     | 

     |  ----------------------------------------------------------------------

     |  Class methods defined here:

     | 

     |  combine(...) from builtins.type

     |      date, time -> datetime with same date and time fields

     | 

     |  fromisoformat(...) from builtins.type

     |      string -> datetime from datetime.isoformat() output

     | 

     |  fromtimestamp(...) from builtins.type

     |      timestamp[, tz] -> tz's local time from POSIX timestamp.

     | 

     |  now(tz=None) from builtins.type

     |      Returns new datetime object representing current time local to tz.

     |     

     |        tz

     |          Timezone object.

     |     

     |      If no tz is specified, uses local timezone.

     | 

     |  strptime(...) from builtins.type

     |      string, format -> new datetime parsed from a string (like time.strptime()).

     | 

     |  utcfromtimestamp(...) from builtins.type

     |      Construct a naive UTC datetime from a POSIX timestamp.

     | 

     |  utcnow(...) from builtins.type

     |      Return a new datetime representing UTC day and time.

     | 

     |  ----------------------------------------------------------------------

     |  Static methods defined here:

     | 

     |  __new__(*args, **kwargs) from builtins.type

     |      Create and return a new object.  See help(type) for accurate signature.

     | 

     |  ----------------------------------------------------------------------

     |  Data descriptors defined here:

     | 

     |  fold

     | 

     |  hour

     | 

     |  microsecond

     | 

     |  minute

     | 

     |  second

     | 

     |  tzinfo

     | 

     |  ----------------------------------------------------------------------

     |  Data and other attributes defined here:

     | 

     |  max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)

     | 

     |  min = datetime.datetime(1, 1, 1, 0, 0)

     | 

     |  resolution = datetime.timedelta(microseconds=1)

     | 

     |  ----------------------------------------------------------------------

     |  Methods inherited from date:

     | 

     |  __format__(...)

     |      Formats self with strftime.

     | 

     |  isocalendar(...)

     |      Return a 3-tuple containing ISO year, week number, and weekday.

     | 

     |  isoweekday(...)

     |      Return the day of the week represented by the date.

     |      Monday == 1 ... Sunday == 7

     | 

     |  strftime(...)

     |      format -> strftime() style string.

     | 

     |  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

     | 

     |  ----------------------------------------------------------------------

     |  Class methods inherited from date:

     | 

     |  fromisocalendar(...) from builtins.type

     |      int, int, int -> Construct a date from the ISO year, week number and weekday.

     |     

     |      This is the inverse of the date.isocalendar() function

     | 

     |  fromordinal(...) from builtins.type

     |      int -> date corresponding to a proleptic Gregorian ordinal.

     | 

     |  today(...) from builtins.type

     |      Current date or datetime:  same as self.__class__.fromtimestamp(time.time()).

     | 

     |  ----------------------------------------------------------------------

     |  Data descriptors inherited from date:

     | 

     |  day

     | 

     |  month

     | 

     |  year

   

    class time(builtins.object)

     |  time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object

     | 

     |  All arguments are optional. tzinfo may be None, or an instance of

     |  a tzinfo subclass. The remaining arguments may be ints.

     | 

     |  Methods defined here:

     | 

     |  __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.

     | 

     |  __reduce__(...)

     |      __reduce__() -> (cls, state)

     | 

     |  __reduce_ex__(...)

     |      __reduce_ex__(proto) -> (cls, state)

     | 

     |  __repr__(self, /)

     |      Return repr(self).

     | 

     |  __str__(self, /)

     |      Return str(self).

     | 

     |  dst(...)

     |      Return self.tzinfo.dst(self).

     | 

     |  isoformat(...)

     |      Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].

     |     

     |      timespec specifies what components of the time to include.

     | 

     |  replace(...)

     |      Return time with new specified fields.

     | 

     |  strftime(...)

     |      format -> strftime() style string.

     | 

     |  tzname(...)

     |      Return self.tzinfo.tzname(self).

     | 

     |  utcoffset(...)

     |      Return self.tzinfo.utcoffset(self).

     | 

     |  ----------------------------------------------------------------------

     |  Class methods defined here:

     | 

     |  fromisoformat(...) from builtins.type

     |      string -> time from time.isoformat() output

     | 

     |  ----------------------------------------------------------------------

     |  Static methods defined here:

     | 

     |  __new__(*args, **kwargs) from builtins.type

     |      Create and return a new object.  See help(type) for accurate signature.

     | 

     |  ----------------------------------------------------------------------

     |  Data descriptors defined here:

     | 

     |  fold

     | 

     |  hour

     | 

     |  microsecond

     | 

     |  minute

     | 

     |  second

     | 

     |  tzinfo

     | 

     |  ----------------------------------------------------------------------

     |  Data and other attributes defined here:

     | 

     |  max = datetime.time(23, 59, 59, 999999)

     | 

     |  min = datetime.time(0, 0)

     | 

     |  resolution = datetime.timedelta(microseconds=1)

   

    class timedelta(builtins.object)

     |  Difference between two datetime values.

     | 

     |  timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

     | 

     |  All arguments are optional and default to 0.

     |  Arguments may be integers or floats, and may be positive or negative.

     | 

     |  Methods defined here:

     | 

     |  __abs__(self, /)

     |      abs(self)

     | 

     |  __add__(self, value, /)

     |      Return self+value.

     | 

     |  __bool__(self, /)

     |      self != 0

     | 

     |  __divmod__(self, value, /)

     |      Return divmod(self, value).

     | 

     |  __eq__(self, value, /)

     |      Return self==value.

     | 

     |  __floordiv__(self, value, /)

     |      Return self//value.

     | 

     |  __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.

     | 

     |  __mod__(self, value, /)

     |      Return self%value.

     | 

     |  __mul__(self, value, /)

     |      Return self*value.

     | 

     |  __ne__(self, value, /)

     |      Return self!=value.

     | 

     |  __neg__(self, /)

     |      -self

     | 

     |  __pos__(self, /)

     |      +self

     | 

     |  __radd__(self, value, /)

     |      Return value+self.

     | 

     |  __rdivmod__(self, value, /)

     |      Return divmod(value, self).

     | 

     |  __reduce__(...)

     |      __reduce__() -> (cls, state)

     | 

     |  __repr__(self, /)

     |      Return repr(self).

     | 

     |  __rfloordiv__(self, value, /)

     |      Return value//self.

     | 

     |  __rmod__(self, value, /)

     |      Return value%self.

     | 

     |  __rmul__(self, value, /)

     |      Return value*self.

     | 

     |  __rsub__(self, value, /)

     |      Return value-self.

     | 

     |  __rtruediv__(self, value, /)

     |      Return value/self.

     | 

     |  __str__(self, /)

     |      Return str(self).

     | 

     |  __sub__(self, value, /)

     |      Return self-value.

     | 

     |  __truediv__(self, value, /)

     |      Return self/value.

     | 

     |  total_seconds(...)

     |      Total seconds in the duration.

     | 

     |  ----------------------------------------------------------------------

     |  Static methods defined here:

     | 

     |  __new__(*args, **kwargs) from builtins.type

     |      Create and return a new object.  See help(type) for accurate signature.

     | 

     |  ----------------------------------------------------------------------

     |  Data descriptors defined here:

     | 

     |  days

     |      Number of days.

     | 

     |  microseconds

     |      Number of microseconds (>= 0 and less than 1 second).

     | 

     |  seconds

     |      Number of seconds (>= 0 and less than 1 day).

     | 

     |  ----------------------------------------------------------------------

     |  Data and other attributes defined here:

     | 

     |  max = datetime.timedelta(days=999999999, seconds=86399, microseconds=9...

     | 

     |  min = datetime.timedelta(days=-999999999)

     | 

     |  resolution = datetime.timedelta(microseconds=1)

   

    class timezone(tzinfo)

     |  Fixed offset from UTC implementation of tzinfo.

     | 

     |  Method resolution order:

     |      timezone

     |      tzinfo

     |      builtins.object

     | 

     |  Methods defined here:

     | 

     |  __eq__(self, value, /)

     |      Return self==value.

     | 

     |  __ge__(self, value, /)

     |      Return self>=value.

     | 

     |  __getinitargs__(...)

     |      pickle support

     | 

     |  __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.

     | 

     |  __repr__(self, /)

     |      Return repr(self).

     | 

     |  __str__(self, /)

     |      Return str(self).

     | 

     |  dst(...)

     |      Return None.

     | 

     |  fromutc(...)

     |      datetime in UTC -> datetime in local time.

     | 

     |  tzname(...)

     |      If name is specified when timezone is created, returns the name.  Otherwise returns offset as 'UTC(+|-)HH:MM'.

     | 

     |  utcoffset(...)

     |      Return fixed offset.

     | 

     |  ----------------------------------------------------------------------

     |  Static methods defined here:

     | 

     |  __new__(*args, **kwargs) from builtins.type

     |      Create and return a new object.  See help(type) for accurate signature.

     | 

     |  ----------------------------------------------------------------------

     |  Data and other attributes defined here:

     | 

     |  max = datetime.timezone(datetime.timedelta(seconds=86340))

     | 

     |  min = datetime.timezone(datetime.timedelta(days=-1, seconds=60))

     | 

     |  utc = datetime.timezone.utc

     | 

     |  ----------------------------------------------------------------------

     |  Methods inherited from tzinfo:

     | 

     |  __getattribute__(self, name, /)

     |      Return getattr(self, name).

     | 

     |  __reduce__(...)

     |      -> (cls, state)

   

    class tzinfo(builtins.object)

     |  Abstract base class for time zone info objects.

     | 

     |  Methods defined here:

     | 

     |  __getattribute__(self, name, /)

     |      Return getattr(self, name).

     | 

     |  __reduce__(...)

     |      -> (cls, state)

     | 

     |  dst(...)

     |      datetime -> DST offset as timedelta positive east of UTC.

     | 

     |  fromutc(...)

     |      datetime in UTC -> datetime in local time.

     | 

     |  tzname(...)

     |      datetime -> string name of time zone.

     | 

     |  utcoffset(...)

     |      datetime -> timedelta showing offset from UTC, negative values indicating West of UTC

     | 

     |  ----------------------------------------------------------------------

     |  Static methods defined here:

     | 

     |  __new__(*args, **kwargs) from builtins.type

     |      Create and return a new object.  See help(type) for accurate signature.

posted on 2020-04-19 07:49  jvincent  阅读(650)  评论(0编辑  收藏  举报