1

I want to specify the date of the desired format as a file name in this way ;

During [2019-10-01 09:00 ~ 2019-10-02 08:59:59] Save data to 191001-09.txt

I have no idea about this. I could only follow simple code. Please let me know how to fix it :

def timeStamped (fname, fmt = '19% m% d-% H {fname} '):
    return datetime.datetime.now (). strftime (fmt) .format (fname = fname)
with open (timeStamped ('. txt'), 'a') as f_last:
    f_last.write ('data')
4
  • This article would make things work here. Commented Oct 1, 2019 at 5:18
  • store this into string format and use regex expression. Commented Oct 1, 2019 at 5:24
  • Thanks for your link. but there seems to be no way to set a specific time range. It's too hard for me to have an application. Commented Oct 1, 2019 at 5:31
  • Thank you for letting me know the bypass method, but it's also difficult. I should think more. Thank you both. Commented Oct 1, 2019 at 5:32

1 Answer 1

1

Question: Conditional file name from datetime.now()

  • Import the required objects
    from datetime import datetime, timedelta
    
  • Define a function that gets the desired file name from a datetime.date object:

    def fname_from_date(date):
        # Rule  09:00:00 ~ day + 1 08:59:59 
        midnight = date.replace(hour=0, minute=0, second=0)
        begin_of_day = date.replace(hour=9, minute=0, second=0)
        end_of_day = date.replace(hour=8, minute=59, second=59)
    
        # Are we between 'midnight' and 'end_of_day'
        if date >= midnight and date <= end_of_day:
            date = date - timedelta(days=1)
            print('\tNext day -1: {}'.format(date))
    
        # 191001-09.txt
        fname = date.strftime('%Y%m%d-09')
        return fname
    
  • Test the function def fname_from_date(... with static dates.
    This requires to create a datetime.date object from datestr.
    for datestr in ['2019-10-01 09:00:00', 
                    '2019-10-01 11:01:11', 
                    '2019-10-02 07:07:07', 
                    '2019-10-02 08:59:59']:
        date = datetime.strptime(datestr, '%Y-%m-%d %H:%M:%S')
        print(date)
        fname = '{}.txt'.format(fname_from_date(date))
        print('\t{}'.format(fname))
    

    Output:

    2019-10-01 09:00:00
        20191001-09.txt
    2019-10-01 11:01:11
        20191001-09.txt
    2019-10-02 07:07:07
        Next day -1: 2019-10-01 07:07:07
        20191001-09.txt
    2019-10-02 08:59:59
        Next day -1: 2019-10-01 08:59:59
        20191001-09.txt
    

Usage:

fname = '{}.txt'.format(fname_from_date(datetime.now()))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I'll give it a try.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.