How to get two all dates (and other method summaries for processing datetime) in any time period

Source: Internet
Author: User
Tags glob timedelta

(1) Use the method to obtain all the dates in two any time period, the code is as follows:

#1. Convert a string to a datetime typedefStrtodatetime (datestr,format):returndatetime.datetime.strptime (Datestr,format)#2. Time converted to string, formatted as 2008-08-02defdatetostr (date):returnSTR (date) [0:10]#3, two days apart, for example: 2008-10-03 and 2008-10-01 are two days apartdefDateDiff (begindate,enddate): Format="%y/%m/%d"; BD=Strtodatetime (Begindate,format) Ed=strtodatetime (enddate,format) oneday=datetime.timedelta (Days=1) Count=0 whilebd!=ed:ed=ed-oneday Count+=1returnCount#4. Get all time of two time period, return listdefgetDays (begindate,enddate): Format="%y/%m/%d"Ed=strtodatetime (enddate,format) oneday=datetime.timedelta (Days=1) Num=datediff (begindate,enddate) +1Li=[]     forIinchRange (0,num): Li.append (Datetostr (ed)) Ed=ed-onedayreturnLi

(2) Set the start and end date (January 1, 2000 as of today 's date), the code is as follows:

def get_today ():    time.localtime (Time.time ())    = Time.strftime ('%y-%m-%d' , Time.localtime (Time.time ()))     return Tdate

(3) Run the following code in the main function to get all dates from January 1, 2000 to today.

def main ():p rint getDays (' 2000-01-01 ', Get_today ()) If __name__ = = ' __main__ ':    Main ()

In addition, there are a few other date-time processing summary of the small method, for informational purposes only. (from:http://www.linux-field.com/archives/360)

#8. Gets the current year is a stringdefgetYear ():returnSTR (Datetime.date.today ()) [0:4]   #9. Gets the current month is a stringdefgetMonth ():returnSTR (Datetime.date.today ()) [5:7]  #10. Gets the current day is a stringdefGetDay ():returnSTR (Datetime.date.today ()) [8:10]     defGetnow ():returnDatetime.datetime.now ()PrintGettoday ()PrintGetyesterday ()PrintGetdaysbynum (3)  PrintGetDays ('2008-10-01','2008-10-05')  Print '2008-10-04 00:00:00'[0:10]  PrintSTR (getYear ()) +getmonth () +GetDay ()PrintGetnow ()#11. Format the string as time    Importdatetime>>> s="2006-1-2"    PrintDatetime.datetime.strptime (s),"%y-%m-%d")    2006-01-02 00:00:00Import Time>>> s="2006-1-2">>> Time.strptime (s),"%y-%m-%d")    >>> fromTimeImport* >>> strftime ("%y-%m-%d%h:%m:%s", LocalTime ())'2011-10-12 03:00:58'#12. Convert a format string to a timestamp>>> A ="Sat Mar 22:24:24">>> B = Mktime (Strptime (A,"%a%b%d%h:%m:%s%Y"))    >>>Printb1238250264.0 >>>#13. DateTime Example-----------------Demo Calculation of two date difference days>>>Importdatetime>>> D1 = Datetime.datetime (2005, 2, 16)>>> D2 = Datetime.datetime (2004, 12, 31)>>> (D1-D2). Days47Shows examples of calculation run times, displayed in secondsImportDatetimestarttime=Datetime.datetime.now ()#long runningEndtime =Datetime.datetime.now ()Print(Endtime-starttime). Seconds#14. Python takes a few days before the date>>> fromDatetimeImportTimedelta, Date>>>PrintDate.today () + timedelta (days =-2) (not a bit like date-d?)2011-10-09 >>>demonstrates the time to calculate the current time backwards by 10 hours. >>> D1 =Datetime.datetime.now ()>>> d3 = d1 + Datetime.timedelta (hours=10)>>>D3.ctime () The classes used in this book are: DateTime and Timedelta two. They can be added and reduced between each other. Each class has some methods and properties to view the specific values. #15. Returns a list of dates relative to today based on a number of starting dayssuch as mydate (0). Getdaysbynum (1, 7) will get a list of dates from the week beginning yesterday. classmydate:def __init__(self, i): self.i=IdefGetdaysbynum (self, St, en): Today= Datetime.date.today () + Datetime.timedelta (-self.i) Oneday= Datetime.timedelta (Days=1)        GlobalYesterday yesterday= Today-oneday Li= []         forIinchrange (0, en): Today= Today-oneday li.append (str (today). Replace ("-",""))        returnLi[st-1: en]#16, Glob: You can use a simple method to match all subdirectories or files under a directory, the usage is also very simple. 3.1Glob.glob (regression) returns a list3.2Glob.iglob (regression) returns a walker

How to get two all dates (and other method summaries for processing datetime) in any time period

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.