A collection of questions and answers about date-time processing in Python _python

Source: Internet
Author: User
Tags datetime python script timedelta in python

How to install Setuptools module without generating egg compression package but source code

Q: How to install the Setuptools module does not generate egg compression package But the source code, so that sometimes can be modified to debug
A: In fact very simple, in the setup.py in the Setup function to add zip_safe=false, parameters can be.

This installation is no longer a egg file, but a directory structure like the previous one.

How to tell if a string contains only numeric characters
This is the discussion you see on the Python.list mailing list.

Q: How to Tell if a string contains only numeric characters

A: One method is A.isdigit (). However, this method is not valid for numeric strings that contain positive and negative numbers, so it is more accurate:
Try
x = Int (apossibleint)
... do something with x ...
Except ValueError:
... do something else ...

This is more accurate and more adaptable. But if you are convinced that there is no sign, it is more convenient to use the IsDigit () method of the string.

Know one day how to get the date of last week
This is a question that someone asked me to record in the following:

Q: I'm going to write a little program like this, write a Python script to return the days of the last week in the format "YYYYMMDD" such as the date is 20051122, the return result is: ["20051113", "20051114", "" 20051115 "," 20051116 "," 20051117 "," 20051118 "," 20051119 "]

A: First, convert the ' YYYYMMDD ' of the string to (year, Mon, day), simple to:
>>> date = ' 20051122 '
>>> year, Mon, day = Int (date[:4]), int (date[4:6]), int (date[6:])

    then get a DateTime object using datetime
         >> > Import datetime
         >>> d = datetime.datetime (year, Mon , day)
    because the DateTime object can get a number of days of Sunday (weekday), based on this number forward.
         >>> d.weekday ()
          1

The

    document says that Monday is 0, then it's Tuesday. Look at your request is the first day starting from Sunday, so last Saturday is: The specified date-its Sunday number 2
    know that Saturday is the day of the last week.
          >>> B = D-datetime.timedelta (D.weekday () + 2)
          >>> days = []
         >>> to I in Range (6,-1,-1):
         ...   c = B-datetime.timedelta (i)
         ...   days.append (c.strftime ('%y%m%d '))
          >>> days
         [' 20051113 ', ' 20051114 ', ' 20051115 ', ' 20051116 ', ' 20051117 ', ' 20051118 ', ' 20051119 ']

    How to intercept a specified length of Chinese characters

    Q: I want to intercept a string of characters of a specified length, but don't want to have half Chinese characters, How to make it simpler
    A: You can consider intercepting by length and then Unicode, and if it succeeds, return it, and if it fails, reduce the length by 1. The sample program is:
        #coding =GBK
        def clip_hz (S, length):
            t = s[:length]
            Try:
                 Unicode (t, ' GBK ')
             except:
                 t = s[:length-1]
            Return T

A = ' Zhonghua 2 people as Republic '
if __name__ = = ' __main__ ':
Print Clip_hz (A, 9)
Print Clip_hz (A, 10)
Print Clip_hz (A, 11)
Print Clip_hz (A, 12)

how to easily go to the command line to run a program under Windows

Executing a python program in the cmd window under Windows, I usually do this:

1. Execute a REG file, which reads:

Copy Code code as follows:

Windows Registry Editor Version 5.00
[Hkey_classes_rootdirectoryshellcmdcommand]
@= "cmd.exe/k" CD%l ""


Its role is to add a menu to the right-click menu on your resource manager named CMD. Then you click on a directory in the table of contents, then right-click, then execute this cmd menu, will go directly to the directory of the command line.

2. Because you have entered the directory where your Python program is located, run directly under the command line:
Python yourprog.py can be.

The premise is that you have added the Python installation directory to the environment variable in PATH.

Re-set the search path for the package to facilitate the import of the child modules
Maybe this topic is a bit scary, but it's really hard to express, this is a piece of code I saw when I read Taskcoach.
Q: I have a package that has been installed in the Python lib/site-packages directory, I can import the X-packet sub module through the import x.sub, but I would like to use import sub as a convenience to introduce the Sub module, there is no such Method

A: Do a little simple work.
Import x

Libpath = x.__path__[0]
Sys.path.insert (0, Libpath)
del X

First import the x package, get the path to it, and then add the path to the front of the Sys.path (Python's Module search path). Then remove the X module. When you import a sub later, you can import it by using only the import sub.
Add this code to the startup code to execute it and it will be in effect for the rest of the time.
But instead of using inserts to handle the Taskcoach, instead of using append, I don't think it's very good. So if you have a module in front of the X package that has the same name as your sub module, it's a hassle, or a front cover.
However, you can also import it using the From X Import sub method, which is easier to understand and standard. The above technology is very interesting will be included, see the situation everyone self use it.

How a child module shares information about a parent module

Q: A module A calls a module B, then b How to access the data in module a

A: Very simple, in module B to import a module can

In fact, this can not be regarded as a skill, and many people may have done so. The reason for writing it is to remind you that what you think is possible is a workable solution. Because I have encountered such a problem before, but also think of this method, but it does not feel good. But after looking at the source code of CherryPy, it is doing so. So I think this is actually a workable solution.

    How to calculate the time difference

    Q: How to easily calculate the two-hour differences, such as two times a few days, hours, etc.

    A: Using the DateTime module is a convenient way to solve this problem, for example:
        >>> Import datetime
        >>> d1 = datetime.datetime (2,)
        >>> D2 = Datetime.datetime (a)
         >>> (D1-D2). Days
       
  The    example shows a calculation that calculates the number of days between two dates.
        import datetime
        StartTime = Datetime.datetime.now ()
        #long running
         endtime = Datetime.datetime.now ()
        Print (endtime-starttime). Seconds

The example above demonstrates the calculation of the elapsed time, shown in seconds.
>>> D1 = Datetime.datetime.now ()
>>> d3 = d1 + Datetime.timedelta (hours=10)
>>> D3.ctime ()
The previous example shows the time to calculate the current time back 10 hours.

Its commonly used classes are: datetime and Timedelta two. They can add and subtract from each other. Each class has methods and properties to view specific values, such as datetime can view: Days, hours (hour), Weeks (Weekday ()), Timedelta can view: days, seconds (seconds), and so on.

How to get the user's starting directory

Q: I am designing a cross-platform application, is there a unified way to get a user's starting directory

A: User's starting directory here I refer to the directory where the data is stored, which, depending on the user, can be saved by the user from the data. There's not a unified way, and here's a function I see that can do this:
Def gethomedir ():
"Try to find User's home directory, otherwise return current directory."
Try
Path1=os.path.expanduser ("~")
Except
Path1= ""
Try
path2=os.environ["Home"]
Except
Path2= ""
Try
path3=os.environ["UserProfile"]
Except
Path3= ""

If not os.path.exists (path1):
If not os.path.exists (path2):
If not os.path.exists (PATH3):
Return OS.GETCWD ()
Else:return Path3
Else:return path2
Else:return path1

Remember to import the OS and Os.path modules before use.

Viewing data in Unicode format

Q: If I have data in Unicode format, such as a list, how can I print out a format that can be displayed, I don't want to see U ' uxxxx ' like this
A: I've written a small function that can do this, but it's not optimized. I think it's best to modify the pprint.py module if you want to show the beauty, but simply use it for debugging. May be a bit of use:)
Def uni_prt (A, Encoding=none):
Import Sys
s = []
If not encoding:
encoding = sys.getdefaultencoding ()
If Isinstance (A, (list, tuple)):
If Isinstance (A, list):
S.append (' [')
Else
S.append (' (')
For I, K in Enumerate (a):
S.append (Uni_prt (k, encoding))
If I<len (a)-1:
S.append (', ')
If Isinstance (A, list):
S.append ('] ')
Else
S.append (') ')
Elif Isinstance (A, dict):
For I, K in Enumerate (A.items ()):
Key, value = k
S.append (' {%s:%s} '% (Uni_prt (key, encoding), UNI_PRT (value, encoding))
If I<len (A.items ())-1:
S.append (', ')
Elif isinstance (A, str):
S.append ("'%s '"%a)
Elif Isinstance (A, Unicode):
S.append ("'%s '"% A.encode (encoding))
Else
S.append (str (a))
Return ". Join (s)

    execution such as:
    >>> a=unicode (' China ', ' cp936 ')
    > >> print Uni_prt ([a]*3, ' cp936 ')
    [' China ', ' China ', ' China ']
The second parameter is the encoding used for Unicode character conversions. The default is the system default encoding.

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.