For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

Have problem getting the correct date format while print



  • Hello, this is the code I use to print the log.

    def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))  
    

    The output:
    Starting Portfolio Value: 100000.00
    2020-05-04, Close, 8871.96
    2020-05-05, Close, 8867.83
    2020-05-05, Close, 8901.65
    2020-05-05, Close, 8858.35
    2020-05-05, Close, 8879.58

    However, I wanted the date to be shown as 2020-05-04 16:30:00 (%Y-%m-%d %H:%M:%S), like how I specified for Data Feed, not just showing date only. Also, how can I change the date to UTC+8?

    Many Thanks.



  • @kian-hong-Tan said in Have problem getting the correct date format while print:

    dt = dt or self.datas[0].datetime.date(0)

    When setting dates in backtrader, datetime is used. The first part:

    self.datas[0].datetime
    

    gets datetime object. The ending will give the format of date, time, or datetime. The endings are:

    datetime(0)  # format is %Y-%m-%d %H:%M:%S
    date(0)  # format is %Y-%m-%d
    time(0) # format is %H:%M:%S
    

    As a standard procedure, at the beginning of my strategy class next() method, as well as in analyzers and indicators where needed, I put the following code:

    # Current bar datetime, date, and time.
    dt = self.data.datetime.datetime()
    date = self.data.datetime.date()
    time = self.data.datetime.time()
    

    This allows me to grab time and date information in an easy, concise, and consistent way during programming.



  • @run-out Tks for clarifying this. Very helpful information! :)


Log in to reply
 

});