Python time, datetime module learning to use __python

Source: Internet
Author: User
Tags date1 local time month name string format time interval timedelta
In the time to do the problem with a few topics need to be timestamp, Datetime, UTC a few times between the conversion, just know that Python provides a very convenient and powerful time processing module, Master Good to use it will be very convenient, here to spend a little time dedicated to the online collection of information, Sorted out, the content is from the Internet, put here, the most important as the record of learning, convenient to use when the time does not need to bother to go to the query, but also hope to give the needs of friends to provide convenient, give a reference to the source, if necessary can also go directly to the source site to learn:
#!/usr/bin/env python #encoding: utf-8 ' reference source: http://www.jb51.net/article/111303.htm http://www.jb51.net/article/
31129.htm http://www.jb51.net/article/63654.htm http://www.jb51.net/article/67828.htm function: Python time module datetime learning using Introduction: Python provides several built-in modules for manipulating datetime, like the calendar,time,datetime datetime module, which defines two constants: DateTime. Minyear and Datetime.maxyear, respectively, representing the minimum and maximum years that a datetime can represent.
of which, minyear = 1,maxyear = 9999. The DateTime module defines 5 classes, namely 1.datetime.date: Class 2.datetime.datetime that represents a date: A class 3.datetime.time representing a DateTime: Class 4, which represents the time. Datetime.timedelta: Represents the time interval, that is, the interval of two points 5.datetime.tzinfo: information about the time zone-------------------------------------------------- ---------------------------------------first, take a look at the Datetime.date class: the date class has three parameters, Datetime.date (year,month,day), Return Year-month-day Method: 1.datetime.date.ctime (), return format such as Sun APR 00:00:00 2017 2.datetime.date.fromtimestamp (timestamp), Returns a Date object based on a given timestamp; Datetime.date.today () acts the same 3.datetime.date.isocalendar (): Returns a tuple of the format (Year,month,day), (2017, 15, 6 ) 4.datetime.date.isoformat (): Returns a format such as Yyyy-mm-dd 5.datetime.date.isoWeekday (): Returns the week (0-6) of the given date, Monday = 0, Sunday =6 6.datetime.date.replace (year,month,day): Replaces the given date, but does not change the original date 7.
Datetime.date.strftime (format): Formats the date time according to the given format. 8.datetime.date.timetuple (): Returns the Time.struct_time object corresponding to the date time.struct_time (tm_year=2017, tm_mon=4, tm_mday=15, Tm_hour =0, Tm_min=0, tm_sec=0, tm_wday=5, tm_yday=105, Tm_isdst=-1) 9.datetime.date.weekday (): The week of the return date format symbol for time date in Python:%y Two-digit year representation (00-99)%Y Four-digit year representation (000-9999)%m month (01-12)%d month (0-31)%H 24-hour system hours (0-23)%I 12 hours (01-12)%m minutes (00=59)%s seconds (00-59)%a Local simplified week name%a Local full week name%b locally simplified month name%b Local full month name%c local corresponding date representation and time for%j year (001 -366)%p local a.m. or p.m. The number of weeks in the year (00-53) Sunday is the beginning of the week%w Week (0-6), Sunday is the beginning of the week%w the number of weeks in a year (00-53) Monday is the start of the week%x local corresponding date for %Z the name of the current time zone to the% per cent itself two, look at the datetime of the Timer class time class has 5 parameters, Datetime.time (hour,minute,second,microsecond,tzoninfo), return 08
: 29:30 1.datetime.time.replace () 2.datetime.time.strftime (format): Returning time in format Format 3.datetime.time.tzname (): Return to the time zone name 4.datetime.time.utcoffset (): Returns the time offset of a time zone third, DateTime datetime class DateTime class has a number of parameters, DateTime (year, month, day[, hour[, minute[, second[, Microsecond[,tzinfo]]], return to the date of day, minutes and seconds Datetime.datetime.ctime () Datetime.datetime.now (). Date (): Returns the date portion of the current datetime Datetime.datetime.now (). Time ()
: Returns the time portion of the current datetime Datetime.datetime.fromtimestamp () Datetime.datetime.now (): Returns the current system time Datetime.datetime.replace () Datetime.datetime.strftime (): Converted from date format to string format Datetime.datetime.now (). Strftime ('%b-%d-%y%h:%m:%s ') ' apr-16-2017 21:01:35 ' Datetime.datetime.strptime (): converted from string format to date format datetime.datetime.strptime (' apr-16-2017 21:01:35 ', '%b-%d-%y% 
h:%m:%s ') 2017-04-16 21:01:35 Four, DateTime Timedelta class Datetime.datetime.timedelta used to compute the difference between two dates ' ' from datetime import * Import time print ' Date.max: ', Date.max print ' date.min: ', date.min print ' Date.today (): ', Date.today () print ' date. Fromtimestamp (): ', Date.fromtimestamp (Time.time ()) now = Date (a) tomorrow = Now.replace (day = modified) print ' n ow: ', now, ', Tomorrow: ', Tomorrow print ' Timetuple (): ', now.timetuple () print ' Weekday (): ', now.Weekday () print ' Isoweekday (): ', Now.isoweekday () print ' Isocalendar (): ', Now.isocalendar () print ' Isoformat (): ', now.i Soformat () ' Date also overloads some operations that allow us to do the following: date2 = date1 + Timedelta # date plus an interval, return a new Date object (Timedelta will be introduced below to indicate the time Interval) date2 = date1-timedelta # date spacer interval, returns a new Date object Timedelta = date1-date2 # Two date subtraction, returns a time interval object date1 < Date2 # Two 
Date: When you are working on a date, you should prevent the date from exceeding the range it can represent.  
' Now = Date.today () tomorrow = now.replace (day = 7) Delta = tomorrow-now print ' Now: ', now, ' Tomorrow: ', tomorrow print ' Timedelta: ', Delta print now + Delta print tomorrow > Now ' the Time Class times class, which consists of hours, minutes, seconds, and microseconds. I'm not from Mars. The constructor for the time class is as follows: Class Datetime.time (hour[, minute[, second[, microsecond[, Tzinfo)]]: The meaning of each parameter is not explained, Note here the parameter tzinfo, which represents the time zone information. 

Note the range of parameters: Hour range is [0], minute range is [0], second range is [0], microsecond range is [0, 1000000]. class attributes defined by the time class: the minimum and maximum times that the time.min, Time.max:time class can represent. Among them, Time.min = time (0, 0, 0, 0), Time.max = time (23, 59, 59, 999999); Time.resoLution: The smallest unit of time, here is 1 microseconds; the instance methods and properties provided by The Times class: Time.hour, Time.minute, Time.second, Time.microsecond: Time, minutes, seconds, microseconds; · Time.tzinfo: time zone information; time.replace ([hour[, minute[, second[, microsecond[, Tzinfo]]]: Creates a new Time object, with the time, minutes, seconds, Microseconds replaces the attributes in the original object (the original object remains unchanged); Time.isoformat (): Returns a string representation of the format "HH:MM:SS"; time.strftime (FMT): Returns a custom formatted string ' from DATETIME Import * tm = time (+) print ' TM: ', TM print ' hour:%d, minute:%d, second:%d, microsecond:%d '% (tm . hour, Tm.minute, Tm.second, tm.microsecond) TM1 = tm.replace (hour =) print ' TM1: ', TM1 print ' Isoformat (): ', Tm.iso Format () ' DateTime class DateTime is a combination of date and time, including all information about date and time. Its constructors are as follows: Datetime.datetime (year, month, day[, hour[, minute[, second[, microsecond[, Tzinfo]]], and the meaning of each parameter is the same as the date, 

In the constructor of time, be aware of the range of parameter values. Class attributes and methods defined by a DateTime class: The minimum and maximum values that can be expressed by Datetime.min, Datetime.max:datetime, and datetime.resolution:datetime smallest units;
Datetime.today (): Returns a DateTime object that represents the current local time; DateTime.Now ([TZ]): Returns a DateTime object that represents the current local time, and if a parameter tz is supplied, gets the TZ local time of time zone referred to as parameter; Datetime.utcnow (): Returns a DateTime object for the current UTC time; Datetime.fromtimestamp (timestamp[, TZ]): Creates a DateTime object based on the timestamp, Parameter TZ specify time zone information; Datetime.utcfromtimestamp (timestamp): Creates a DateTime object based on the timestamp; datetime.combine (date, time): Based on date and time, 

Creates a DateTime object; datetime.strptime (date_string, format): Converts a format string to a DateTime object; ' from datetime import * Import time print ' Datetime.max: ', Datetime.max print ' datetime.min: ', datetime.min print ' datetime.resolution: ', Datetime.resolution print ' Today (): ', Datetime.today () print ' Now (): ', DateTime.Now () print ' UtcNow (): ', Datetime.utcno W () print ' Fromtimestamp (tmstmp): ', Datetime.fromtimestamp (Time.time ()) print ' Utcfromtimestamp (tmstmp): ', Datetime.utcfromtimestamp (Time.time ()) ' datetime.year, month, day, hour, minute, second, microsecond, Tzinfo: Datetime.date (): Gets the Date object; datetime.time (): Gets the time object; datetime.replace ([year[, month[, day[, hour[, minute[, second[, microsecond[, Tzinfo]]]: datetime.timetuple () datetime.utctimetuple () DatetiMe.toordinal () datetime.weekday () Datetime.isocalendar () datetime.isoformat ([Sep]) datetime.ctime () : Returns a C-format string of datetime equivalent to Time.ctime (Time.mktime (Dt.timetuple ()); datetime.strftime (format) like date, You can also compare two DateTime objects, or subtract a time interval object, or a date time plus an interval to return a new DateTime object. No detailed examples are provided here. The format string datetime, date, and time provide the Strftime () method, which receives a format string representing the string representation of the DateTime. 

The following table is drawn from the Python manual, and I have made a simple translation (a little bit of the Interpreter ~ ~). Format character meaning%a week's shorthand. such as Wednesday for the web%a week full write. For example, Wednesday is a shorthand for Wednesday%b month. such as April for the APR%b month full write. As in April, the string representation of the April%c: DateTime. (For example: 04/07/10 10:43:39)%d: Days in this month (is the day of the week)%f: microseconds (range [0,999999])%H: Hours (24 hours, [0,])%I: Hours (12 hours, [0, one])%j: Day Days in the year [001,366] (is the day of the current year)%m: Month ([01,12])%m: minutes ([00,59])%p:am or PM%s: seconds (range is [00,61], why not [00, 59], reference Python manual ~_~)%u : Week in the week of the Year of the year of the first few weeks, Sunday as the first day of the week%w: Today in this week's number of days, the range is [0, 6],6 for Sunday%w: Week in the year (is the week of the year), Monday as the first day of the week%x: date string (such as: 04/07/10)%x: Time A string (such as: 10:43:39)%y:2 The year represented by a number%y:4 a number%z: the interval from UTC (If it is local time, an empty string is returned)%z: Time zone name (if local time, return an empty string) percent%:%%% ' ''
DT = DateTime.Now () print ' (%y-%m-%d%h:%m:%s%f): ', Dt.strftime ('%y-%m-%d%h:%m:%s ') print ' (%f%y-%m-%d) : ', Dt.strftime ('%y-%m-%d%i:%m:%s%p ') print '%%a:%s '% dt.strftime ('%a ') print '%%a:%s '% dt.strftime ('%a ') prin T '%%b:%s '% dt.strftime ('%b ') print '%%b:%s '% dt.strftime ('%b ') print ' Date time%%c:%s '% dt.strftime ('%c ') print ' Day Period%%x:%s '% dt.strftime ('%x ') print ' time%%x:%s '% dt.strftime ('%x ') print ' Today is this week's%s day '% dt.strftime ('%w ') print ' Today is 
The first%s days '% dt.strftime ('%j ') print ' This week is this year's%s week '% dt.strftime ('%u ') #Python中datetime常用时间处理方法 import datetime # Get the current time D1 = Datetime.datetime.now () Print D1 # current time plus half hour d2 = D1 + Datetime.timedelta (hours=0.5) Print d2 # format string output D3 = D2.str Ftime ('%y-%m-%d%h:%m:%s ') Print D3 # Converts a string to a time type # D4 = datetime.datetime.strptime (date, '%y-%m-%d%h:%m:%s.%f ') # print D 4 #获取本周和本月第一天的日期: Def first_day_of_month (): "Get the first day of this 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 ()) #now方法有个参数tz, set the time zone type. If it's not the same as the method today's effect now = Datetime.datetime.now () #UTC时间 datetime.datetime.utcnow () attrs = [("Year", "Years"), (' Month ', ' month '), ("Day", "th"), (' Hour ', "hours"), (' Minute ', ' min '), (' second ', ' seconds '), (' microsecond ', ' millisecond '), (' Min ', ' min '), (' Max ', ' Max '),] for k,v In attrs: "now.%s =%s #%s"% (K,getattr (now, K), V) If __name__ = "__main__": This_week = First_day_of_week () las T_week = This_week-datetime.timedelta (days=7) This_month = First_day_of_month () Last_month = this_month-datetime.t Imedelta (days= (This_month-datetime.timedelta (Days=1)). Day) Print This_week print last_week print This_month prin

 T Last_month

Simple Run the result:

date.max:9999-12-31 date.min:0001-01-01 date.today (): 2017-04-19 date.fromtimestamp (): 2017-04-19 now:2010-04-06, Tom Orrow:2010-04-07 timetuple (): Time.struct_time (tm_year=2010, tm_mon=4, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_ Wday=1, tm_yday=96, Tm_isdst=-1) weekday (): 1 Isoweekday (): 2 Isocalendar (): (2) Isoformat (): 2010-04-06 now:20 17-04-19 tomorrow:2017-04-07 Timedelta: -12 days, 0:00:00 2017-04-07 False tm:23:46:10 hour:23, minute:46, second:10 , microsecond:0 tm1:20:46:10 Isoformat (): 23:46:10 datetime.max:9999-12-31 23:59:59.999999 datetime.min:0001-01-01 00: 00:00 datetime.resolution:0:00:00.000001 today (): 2017-04-19 09:48:00.346997 Now (): 2017-04-19 09:48:00.347013-UtcNow ( ): 2017-04-19 01:48:00.347024 Fromtimestamp (tmstmp): 2017-04-19 09:48:00.347030 (utcfromtimestamp): 2017-04-19 
01:48:00.347041 (%y-%m-%d%h:%m:%s%f): 2017-04-19 09:48:00 347047 (%y-%m-%d%h:%m:%s%p): 17-04-19 09:48:00 AM%a:wed %a:wednesday%b:apr%b:april DateTime%c:wed APR 19 09:48:00 2017 date%x:04/19/17 time%x:09:48:00 today is the 3rd day of the week today is this year's 109th day this week is this year 16th week 2017-04-19 09:48:00.3471 96 2017-04-19 10:18:00.347196 2017-04-19 10:18:00 2017-04-17 2017-04-10 2017-04-01 2017-03-01


The next one is a few time conversion programs, from http://www.jb51.net/article/63654.htm here for learning purposes only, as their own code notes:
#coding =utf-8 ' ' Python Timestamp, datetime, convert practice between UTC times ' import time import Datetime #一, datetime into Timestamp def dat Etime2timestamp (DT, convert_to_utc=false): ' Converts a DateTime object to UNIX timestamp in milliseconds. ' If isinstance (DT, datetime.datetime): If CONVERT_TO_UTC: # is converted to UTC time dt = dt + Datetime.timedelta (hours=-  8) # China default time zone timestamp = total_seconds (Dt-epoch) return long (timestamp) return DT #二, timestamp converted to datetime def Timestamp2datetime (timestamp, convert_to_local=false): ' Converts UNIX timestamp to a DateTime object. ' If Isinstance (timestamp, (int, long, float): dt = Datetime.datetime.utcfromtimestamp (timestamp) if Convert_ To_local: # Convert to local time dt = dt + Datetime.timedelta (hours=8) # China default time zone return DT return timestamp #三, current UTC time t Imestamp def timestamp_utc_now (): Return Datetime2timestamp (Datetime.datetime.utcnow ()) #四, timestamp def times of current local time Tamp_now (): Return Datetime2timestamp (DATETIME.DAtetime.now ()) #五, UTC time converted to local time # need to install Python-dateutil # Ubuntu: sudo apt-get install Python-dateutil # or use Pip:sudo pip I  Nstall python-dateutil from dateutil import tz from Dateutil.tz import tzlocal from datetime import datetime Time Zone name Print DateTime.Now (tzlocal ()). Tzname () # UTC Zone From_zone = Tz.gettz (' UTC ') # The Zone To_zone = tz. Gettz (' CST ') UTC = Datetime.utcnow () # Tell the DateTime object, it ' s in UTC time zone UTC = Utc.replace (tzinfo=fr Om_zone) # Convert time zone local = Utc.astimezone (to_zone) print datetime.strftime (local, "%y-%m-%d%h:%m:%s") # D EF Get_prev_timestamp (tart_ts, Interval = 3): # Start_array = Datetime.datetime.utcfromtimestamp (start_ts) # Start      _array = Start_array + Datetime.timedelta (hours=8) # prev_time = (Start_array-datetime.timedelta (days = interval)) #  prev_ts = Int (Time.mktime (Prev_time.timetuple ())) # return PREV_TS # def get_end_timestamp (start_ts, Interval = ): # start_date = Datetime.datetime.utcfromtimestamp (start_ts) # start_date = start_date + Datetime.timedelta (hours=8) # end_date = Start_date + datetime.timedelta (minutes = interval) # end_ts = Int (Time.mktime (End_date.timetuple ())) # return E ND_TS # def get_seven_day_ago (day = 7): # human = {' d ': 86400} # now = Int (Time.time ()) # ts = now-day * H uman[' d '] # return str (ts) # start_ts = Time.time () # Print Get_seven_day_ago ()

Simple Run the result:

Cst
2017-04-19 09:50:02

The sense datetime module is powerful, often used in Python projects, and mastering some of the most useful functions can be a great help for productivity improvements in later work.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.