Python time datetime Common processing method

Source: Internet
Author: User
Tags timedelta

Common time conversion and processing functions:

Importdatetime#Get current TimeD1 =Datetime.datetime.now ()PrintD1#The current time plus half an hourD2 = D1 + Datetime.timedelta (hours=0.5)PrintD2#format string OutputD3 = D2.strftime ('%y-%m-%d%h:%m:%s')PrintD3#Convert A string to a time typeD4 = Datetime.datetime.strptime (date,'%y-%m-%d%h:%m:%s.%f')PrintD4

Get dates for this week and the first day of the month:

#-*-coding:utf-8-*-Importdatetimedeffirst_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)    returnDatetime.date.today ()-Datetime.timedelta (Days=datetime.datetime.now (). day-1)defFirst_day_of_week ():" "get the first day of the week: return:" "    returnDatetime.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)PrintThis_weekPrintLast_weekPrintThis_monthPrintLast_month

Python time datetime Common processing method

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.