Commonly used datetime time processing method in Python, pythondatetime
Common time conversion and processing functions:
Import datetime # obtain the current time d1 = datetime. datetime. now () print d1 # The current time plus half an hour d2 = d1 + datetime. timedelta (hours = 0.5) print d2 # Format String output d3 = d2.strftime ('% Y-% m-% d % H: % M: % s ') print d3 # convert string to time type d4 = datetime. datetime. strptime (date, '% Y-% m-% d % H: % M: % S. % F') print d4
Obtain the date of this week and the first day of this month:
#-*-Coding: UTF-8-*-import datetimedef first_day_of_month (): ''' get the first day of the month: return: ''' # now_date = datetime. datetime. now () # return (now_date + datetime. timedelta (days =-now_date.day + 1 )). replace (hour = 0, minute = 0, second = 0, # microsecond = 0) return datetime. date. today ()-datetime. timedelta (days = datetime. datetime. now (). day-1) def first_day_of_week (): ''' get the first day of the week: return: ''' return datetime. date. today ()-datetime. timedelta (days = datetime. date. today (). weekday () if _ name _ = "_ main _": this_week = first_day_of_week () last_week = this_week-datetime. timedelta (days = 7) this_month = first_day_of_month () last_month = this_month-datetime. timedelta (days = (this_month-datetime. timedelta (days = 1 )). day) print this_week print last_week print this_month print last_month
#! /Usr/bin/python # coding = utf-8import datetime "" datetime is powerful to support 0001 to 9999 "the current time returns a datetime type now method with parameter tz, set the time zone type. If the effect is not the same as that of the today method, "" now = datetime. datetime. now () # UTC time datetime. datetime. utcnow () attrs = [("year", "year"), ('month', "month"), ("day", "day "), ('hour ', "hour"), ('minute', "minute"), ('second', "second"), ('microsecond', "millisecond "), ('Min', "min"), ('max ', "max"),] for k, v in attrs: "now. % s = % s # % s "% (k, getattr (now, k), v)" returns a time Structure "now. timetuple () "returns a date type" "now. date () "returns a time type" now. time () "current day of the week. Monday is 0, and week is 6. Note that this is a method, not a property. "" Now. weekday () "current day of the week. Monday is 1, week is 7. Note that this is a method, not a property. "Now. isoweekday ()" modifies the current time. For example, change it to "" now. replace (day = 1) past = datetime. datetime (, 16) "timedelta type" "now-past" converted to string Detailed Rules "strdatetime = now. strftime ("% Y-% m-% d % H: % M: % S") "string generation datetime object" datetime. datetime. strptime (strdatetime, "% Y-% m-% d % H: % M: % S ")
The above is all the content of this article. I hope you will like it.