Python Date related

Source: Internet
Author: User

Tag: Port calculates des target position nbsp Coding Python3 Basic

Basic date and time conversion issues

You need to perform simple time transitions, such as days to seconds, hours to minutes, and so on.

Solution Solutions

In order to perform conversions and calculations for different time units, use the datetime module. For example, to represent a time period, you can create an timedelta instance as follows:

>>>FromDatetimeImportTimedelta>>>A=Timedelta(Days=2,Hours=6)>>>B=Timedelta(Hours=4.5) >>> c = a + b>>> c. Days2>>> c. Seconds37800>>> c. Seconds /360010.5>>> c. Total_seconds () /360058.5 >>>                

If you want to represent the specified date and time, first create an datetime instance and then manipulate them using standard math operations. Like what:

>>>FromDatetimeImportDatetime>>>A=Datetime(2012,9,23)>>>Print(A+Timedelta(Days=10))2012-10-03 00:00:00>>>>>>B=Datetime(2012,12,21st)>>>D=b -a>>> d days89>>> now = datetime. Today () >>> print (now< Span class= "P" >) 2012-12-21 14:54:43.094063>>> print< Span class= "P" > (now + timedelta ( Minutes=102012-12-21 15:04:43.094063 >>>               

When calculating, it is important to note that datetime leap years are automatically processed. Like what:

>>>A=Datetime(2012,3,1)>>>B=Datetime(2012,2,28)>>>A-BDatetime.timedelta (2)>>>(A-b).  Days2>>> c = datetime( 3, 1)>>> d = datetime( 2, + )>>> (C - d).  Days1>>>              
Discuss

For most basic date and time processing issues, the datetime module is sufficient. If you need to perform more complex date operations, such as processing time zones, blurring time ranges, holiday calculations, and so on, consider using the Dateutil module

Many similar time calculations can be used dateutil.relativedelta() instead of functions. One thing to note, however, is that it fills the gap as it processes the months (and the difference in the number of days). See examples most clearly:

>>> A = DateTime (9, $) >>> A + Timedelta (Months=1) Traceback (most recent call last): File "<stdi N> ", line 1, in <module>typeerror: ' months ' is a invalid keyword argument for this function>>>>>& Gt From Dateutil.relativedelta import relativedelta>>> A + Relativedelta (months=+1) datetime.datetime (2012, 10, 0, 0) >>> A + Relativedelta (months=+4) datetime.datetime (1, 0, 0) >>>>>> # time BETW  Een dates>>> b = datetime (+, +) >>> d = b-a>>> ddatetime.timedelta (*) >>> D = Relativedelta (b, a) >>> Drelativedelta (months=+2, days=+28) >>> d.months2>>> d.days28 >>>




    • Docs»
    • Chapter III: Digital Date and Time»
    • 3.13 Calculating the date of the last Friday
    • Edit on GitHub
3.13 Calculating the date of the last Friday ¶ problem ¶

You need to find the last date of the day of the week, such as Friday.

Solution ¶

Python's datetime modules have tool functions and classes that can help you perform such calculations. Here's a general solution to a problem like this:

#!/usr/bin/env python#-*-Encoding:utf-8-*-"""Topic: The last FridayDesc:""" from datetime Import datetime, Timedeltaweekdays = [' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ',            ' Friday ', ' Saturday ', ' Sunday ']def Get_previous_byday(Dayname, start_date=None):    if start_date  is None:        start_date = datetime.Today()    Day_num = start_date.Weekday()    Day_num_target = weekdays.Index(Dayname)    Days_ago = (7 + Day_num - Day_num_target) % 7    if Days_ago == 0:        Days_ago = 7    target_date = start_date - Timedelta( Days=Days_ago)    return target_date

The following are used in the interactive interpreter:

>>>datetime.Today() # for referenceDatetime.datetime (8, 4, 263076)>>>Get_previous_byday(' Monday ')Datetime.datetime (8, 3, 29045)>>>Get_previous_byday(' Tuesday ') # Previous Week, not todayDatetime.datetime (8, 4, 629771)>>>Get_previous_byday(' Friday ')Datetime.datetime (8, 5, 9, 911393)>>>

Optional start_date parameters can be provided by another datetime instance. Like what:

Get_previous_byday (' Sunday ',datetime( ),  + ))datetime.datetime (0, 0)>>>
Discussion ¶

The above algorithm works by mapping the start date and the target date to the position of the day of the Week (index 0 in Monday), and then using modulo to calculate the number of days before the target date can reach the start date. The result date is then subtracted from the time difference by the start date.

If you're going to do a lot of date calculations like this, you'd better install a third-party package python-dateutil instead. For example, the following is the dateutil same calculation that is performed using the functions in the module relativedelta() :

>>> from datetime Import datetime>>> from Dateutil.relativedelta Import Relativedelta>>> from Dateutil.rrule Import *>>>D = datetime. Now()>>>Print(D)2012-12-23 16:31:52.718111>>># Next Friday>>>Print(D + Relativedelta(Weekday=FR))2012-12-28 16:31:52.718111>>>>>># last Friday>>>Print(D + Relativedelta(Weekday=FR(-1)))2012-12-21 16:31:52.718111>>>
Next Previous

©copyright 2017, bear can. Revision fc3b417c .

Built with Sphinx using a theme provided by Read the Docs.

Python Date related

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.