Python provides multiple built-in modules for date and time operations, such as calendar, time, and datetime. Today, we will mainly discuss how to use datetime. if you need it, you can refer to it. 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.