Home  >  Article  >  Backend Development  >  The time module and datetime module in Python

The time module and datetime module in Python

高洛峰
高洛峰Original
2017-03-01 13:35:081163browse

time module

The time module is a function that contains various operations on time. Although these are often valid, not all methods are valid on all platforms. Time uses struct_time Represents time

import time

# time.struct_time(tm_year=2015, tm_mon=4, tm_mday=24, 
          tm_hour=14, tm_min=17, tm_sec=26, 
          tm_wday=4, tm_yday=114, tm_isdst=0)
# 2015
print time.localtime()
print time.localtime().tm_year

Function

  • time.time(): Returns a timestamp

  • time.asctime([t]): Convert the tuple or struct_time returned by gmtime() and localtime() to string.

  • time.clock(): When called for the first time, return the time when the program is running. After the second call, return the interval from before.

  • time.ctime([secs]) : Convert the timestamp to a time string. If not provided, the current time string is returned, which is the same as asctime(localtime()).

  • time.gmtime([secs] ): Convert timestamp to struct_time in UTC time zone.

  • time.localtime([secs]): Similar to gmtime() but will convert it to local time zone.

  • time.mktime(t): struct_time is converted into a timestamp.

  • time.sleep(secs): The thread delays the specified time, in seconds .

  • time.strftime(format[,t]): Convert a sturc_time or tuple to a string according to the parameters.

  • time. strptime(string[, format]): Contrary to strftime, returns a struct_time.

##

import time

# Fri Apr 24 06:39:34 2015
print time.asctime(time.gmtime())

# 0.0
# None
# 1.01136392961 因计算机而异
print time.clock()
print time.sleep(1)
print time.clock()

# Fri Apr 24 14:42:07 2015
print time.ctime()

# 2015-04-24
print time.strftime('%Y-%m-%d', time.localtime())
# 1429857836.0
print time.mktime(time.localtime())

commonly used in the time module Format string

  • %y Two-digit year 00 ~ 99.

  • %Y Four-digit year 0000 ~ 9999

  • %m month 01 ~ 12.

  • %d day 01 ~ 31.

  • %H Hours 00 ~ 23.

  • %I Hours 01 ~ 12.

  • ##%M Minutes 00 ~ 59.
  • %S seconds 00 ~ 61.

datetime module
datetime module provides date Perform simple or complex operations with time. The datetime module provides the following available types (Available Types).
datetime.MINYEAR and datetime.MAXYEAR module constants represent the range accepted by datetime

    class datetime.date: An idealized date, providing year, month, and day attributes
  • class datetime.time: An idealized time, providing hour, minute, second, microsecond, tzinfo.
  • class datetime.datetime: A combination of date and time. Provides year, month, day, hour, minute, second, microsecond, tzinfo.
  • class datetime.timedelta: Express the subtle difference between the duration of two dates, time and datetime.
  • class datetime.tzinfo: The abstract base of time objects Class.
from datetime import timedelta, datetime

a = datetime.now()
b = timedelta(days=7)

# 7 days, 0:00:00
# 2015-04-14 16:02:39.189000
print b
print a - b

Let’s talk about classes and class methods in detail

date class

A date object represents an idealized date.

  class datetime.date(year, month, day)
    # All arguments are required. Arguments may be ints or longs.
    # 所有参数都是必须的. 参数可能是 int 或 long.
    MINYEAR <= year <= MAXYEAR
    1<= month <= 12
    1<= day <= number of days in the given month and year.(随着月份和年份)

If the parameter is outside the given range, valueError will be thrown.

1. Class method>`date.today()`: Return the current local date, which is equivalent to `date.fromtimestamp(time.time())`.

Return the current local date. This is equivalent to `date.fromtimestamp(time.time())`.



  from datetime import date

  # print 2015-04-21
  print date.today()

2.date.fromtimestamp(timestamp):According to the provided Timestamp returns local date. Timestamp is often used to store time types.

import time
from datetime import date

# 1429587111.21
# 2015-04-21
print time.time()
print date.fromtimestamp(time.time())

3. Class method date.fromordinal(ordinal): According to the provided Gregorian Calendar returns date.(No description)

Class attribute

    date.min: Returns date(MINYEAR, 1, 1).
  • date.max: Returns date(MAXYEAR, 12, 31).
  • date.year: Returns the year, between MINYEAR and MAXYEAR
  • date.month: Returns the month, between 1 and December
  • date.day: Returns between 1 and n.
d = date(2014, 4, 21)
# 2014 4 21
print d.year, d.month, d.day

Instance method

    date.replace(year, month, day): Returns a data object with the same value, except These parameters specify new values ​​for keywords.
  • date.timetuple(): Returns a time.struct_time object.
  • date.toordinal (): Returns a Gregoian Calendar object.
  • date.weekday(): Returns the day of the week. Monday is 0, Sunday is 6.
  • date.isoweekday(): Returns the day of the week. Monday is 1, Sunday is 7.
  • date.isocalendar(): Returns a triple, ( ISO year, ISO week number, ISO weekday).
  • date.isoformat(): Returns a string format of 'YYYY-MM-DD'.
  • date.ctime(): Returns a string date, d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())).
  • date.strftime(format): Returns a string date with custom format.
  • ##
    d = date(2015, 4, 21)
    
    # 2015-04-21
    # 2015-04-21
    # 2015-04-22
    print d
    print d.replace()
    print d.replace(day=22)
    
    # time.struct_time(tm_year=2015, tm_mon=4, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=111, tm_isdst=-1)
    print d.timetuple()
    
    # print 1
    # print 2
    print d.weekday()
    print d.isoweekday()
    
    # print 2015-04-21
    print d.isoformat()
    
    # print 21/04/2015
    print d.strftime(&#39;%d/%m/%y&#39;)

datetime class

The datetime object is a single object that contains information about all date and time objects.

class datetime.datetime(year, month, day[, hour
                    [, minute
                    [, second
                    [, microsecond
                    [, tzinfo]]]]])
  # The year, month and day arguments are required.
  MINYEAR <= year <= MAXYEAR
  1 <= month <= 12
  1 <= day <= n
  0 <= hour < 24
  0 <= minute < 60
  0 <= second < 60
  0 <= microsecond < 10**6

Class method

datetime.today(): Returns the current local datetime. With tzinfo None. This is equivalent to datetime.fromtimestamp(time.time()).
  • datetime.now([tz]): 返回当前本地日期和时间, 如果可选参数tz为None或没有详细说明,这个方法会像today().

  • datetime.utcnow(): 返回当前的UTC日期和时间, 如果tzinfo None ,那么与now()类似.

  • datetime.fromtimestamp(timestamp[, tz]): 根据时间戳返回本地的日期和时间.tz指定时区.

  • datetime.utcfromtimestamp(timestamp): 根据时间戳返回 UTC datetime.

  • datetime.fromordinal(ordinal): 根据Gregorian ordinal 返回datetime.

  • datetime.combine(date, time): 根据date和time返回一个新的datetime.

  • datetime.strptime(date_string, format): 根据date_string和format返回一个datetime.

from datetime import datetime

# 2015-04-21 14:07:39.262000
print datetime.today()

# 2015-04-21 14:08:20.362000
print datetime.now()

# 1429596607.06
# 2015-04-21 14:10:07.061000
t = time.time() 
print t
print datetime.fromtimestamp(t)

from datetime import datetime, date, time

a = date(2015, 4, 21)
b = time(14, 13, 34)

# 2015-04-21 14:13:34
print datetime.combine(a, b)

实例方法

  • datetime.date(): 返回相同年月日的date对象.

  • datetime.time(): 返回相同时分秒微秒的time对象.

  • datetime.replace(kw): kw in [year, month, day, hour, minute, second, microsecond, tzinfo], 与date类似.

其他方法可查看官方文档…

from datetime import datetime, date, time

td = date(2015, 4, 21)
n = time(14, 28, 30)

# 2099-04-21 14:30:42.103000
print datetime.now(0.replace(year=2099)

类属性

  • datetime.min: datetime(MINYEAR, 1, 1).

  • datetime.max: datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999).

实例属性(read-only)

  • datetime.year: 1 至 9999

  • datetime.month: 1 至 12

  • datetime.day: 1 至 n

  • datetime.hour: In range(24). 0 至 23

  • datetime.minute: In range(60).

  • datetime.second: In range(60).

  • datetime.microsecond: In range(1000000).

time类

time 代表本地(一天内)时间.

class datetime.time([hour
          [, minute
          [, second 
          [, microsecond
          [, tzinfo]]]]])
  # All arguments are optional.
  # 所有参数都是可选的.
  0 <= hour < 24
  0 <= minute < 60
  0 <= second < 60
  0 <= microsesond < 10**6

time类就是对时间的一些操作,其功能类似与datetime.其实date和time就是对datetime中日期和时间的操作.

更多Python中的time模块与datetime模块相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn