Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    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

    General Code/Help
    2
    3
    184
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • kian hong Tan
      kian hong Tan last edited by

      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.

      1 Reply Last reply Reply Quote 0
      • run-out
        run-out last edited by

        @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.

        RunBacktest.com

        1 Reply Last reply Reply Quote 1
        • kian hong Tan
          kian hong Tan last edited by

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

          1 Reply Last reply Reply Quote 0
          • 1 / 1
          • First post
            Last post
          Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors