Results 1 to 3 of 3

Thread: Python - Attempting to create directory with the date as the name

  1. #1
    Join Date
    Apr 2006
    Location
    Leeds, England
    Beans
    177
    Distro
    Ubuntu 16.04 Xenial Xerus

    Python - Attempting to create directory with the date as the name

    Hi guys,

    I am beginner trying to use Python to create a directory where today's date is the name.

    This is what I have done so far:

    Code:
    #!/usr/bin/python
    import time, datetime, os
    
    today = datetime.date.today()
    os.mkdir(today)
    This isn't working for me. I get the error:

    TypeError: coercing to Unicode: need string or buffer, datetime.date found

    I have googled for the above phrase & also using keywords Python, unicode, date, but I have not found anything useful.

    Can anyone help please?
    The Ubuntu Counter Project - User number # 6435

  2. #2
    Join Date
    Feb 2007
    Location
    /dev/random
    Beans
    671
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: Python - Attempting to create directory with the date as the name

    Hi,

    Try this:
    Code:
    #!/usr/bin/python
    import time, datetime, os
    
    today = datetime.date.today()  # get today's date as a datetime type
    
    todaystr = today.isoformat()   # get string representation: YYYY-MM-DD
                                   # from a datetime type.
    
    os.mkdir(todaystr)
    Hint: When things don't work as you expect they should in Python the keyword type can save a lot of frustration. Example:

    Code:
    Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:40) 
    [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import time, datetime, os
    >>> today = datetime.date.today()
    >>> os.mkdir(today)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: coercing to Unicode: need string or buffer, datetime.date found
    >>> type(today)
    <type 'datetime.date'>
    >>> todaystr = today.isoformat()
    >>> type(todaystr)
    <type 'str'>
    >>> print todaystr
    2009-02-02
    >>>
    Main system: Dell 1420n - C2D T5250, 4GB RAM, 120GB SATA. Ubuntu 8.04.3.
    Assorted VMs (via VBox). Favorites: Fedora, FreeBSD, Solaris.

  3. #3
    Join Date
    Apr 2006
    Location
    Leeds, England
    Beans
    177
    Distro
    Ubuntu 16.04 Xenial Xerus

    Re: Python - Attempting to create directory with the date as the name

    Many thanks niteshifter. That's just what I needed. Thanks for the 'type' tip as well.

    The Ubuntu Counter Project - User number # 6435

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •