Python: Adding Time in a txt file The Next CEO of Stack OverflowHow do I check whether a file exists without exceptions?Calling an external command in PythonWhat are metaclasses in Python?How can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?How do I list all files of a directory?Does Python have a string 'contains' substring method?Find all files in a directory with extension .txt in Python

How easy is it to start Magic from scratch?

What makes a siege story/plot interesting?

If the heap is initialized for security, then why is the stack uninitialized?

How should I support this large drywall patch?

Apart from "berlinern", do any other German dialects have a corresponding verb?

What does "Its cash flow is deeply negative" mean?

WOW air has ceased operation, can I get my tickets refunded?

Horror movie/show or scene where a horse creature opens its mouth really wide and devours a man in a stables

What can we do to stop prior company from asking us questions?

Why did we only see the N-1 starfighters in one film?

Is it okay to store user locations?

Fastest way to shutdown Ubuntu Mate 18.10

Rotate a column

What does this shorthand mean?

How to count occurrences of text in a file?

Increase performance creating Mandelbrot set in python

What is the purpose of the Evocation wizard's Potent Cantrip feature?

Trouble understanding the speech of overseas colleagues

% symbol leads to superlong (forever?) compilations

Can a single photon have an energy density?

How to be diplomatic in refusing to write code that breaches the privacy of our users

Can I equip Skullclamp on a creature I am sacrificing?

Can a caster that cast Polymorph on themselves stop concentrating at any point even if their Int is low?

Inappropriate reference requests from Journal reviewers



Python: Adding Time in a txt file



The Next CEO of Stack OverflowHow do I check whether a file exists without exceptions?Calling an external command in PythonWhat are metaclasses in Python?How can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?How do I list all files of a directory?Does Python have a string 'contains' substring method?Find all files in a directory with extension .txt in Python










0















I have the below code where it is adds a header to my file. you can see in the header it adds; 'name', 'date' and 'time'.



what i am trying to attempted next is to add another line in the header called 'AddedTime'. this field needs to add 15 mins on top of the current time and output it out into the 'AddedTime' header.



Python code.



stamp = datetime.datetime.now()
Year = str(stamp)[:4]
Month = str(stamp)[5:7]
Day = str(stamp)[8:10]
Hour = str(stamp)[11:13]
Minutes = str(stamp)[14:16]
Seconds = str(stamp)[17:18]
Date = Year + Month + Day
time = Hour + ':' + Minutes + ':' + Seconds

file = 'file.txt'
header_names = 't1':'Test1', 't2': 'Test2','t3':'Test3'
with open(file, 'w', newline='') as f:
f.seek(0,0)
f.writelines("Name: ", file)
f.writelines("Date: ",date)
f.writelines("Time: ",time)
w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='',
extrasaction='ignore')
w.writerow(header_names)
for doc in res['test']['test']:
my_dict = doc['test']
w.writerow(my_dict)
f.seek(0,2)
f.writelines("This is generated using Python")


Current file looks like below. - file.txt



header
Name:file.txt
Date:20190321
Time:9:15:00

data
Test1,Test2,Test3
Bob,john,Male
Cat,Long,female
Dog,Short,Male
Case,Fast,Male
Nice,who,Male


Ideal file output - file.txt



header
Name:file.txt
Date:20190321
Time:09:15:00
AddedTime:09:30:00

data
Test1,Test2,Test3
Bob,john,Male
Cat,Long,female
Dog,Short,Male
Case,Fast,Male
Nice,who,Male


any help will be appreciated.










share|improve this question






















  • Are you trying to retroactively add the line to existing files, or are you just trying to figure out how to add a timedelta to a datetime?

    – Craig Meier
    Mar 21 at 16:41















0















I have the below code where it is adds a header to my file. you can see in the header it adds; 'name', 'date' and 'time'.



what i am trying to attempted next is to add another line in the header called 'AddedTime'. this field needs to add 15 mins on top of the current time and output it out into the 'AddedTime' header.



Python code.



stamp = datetime.datetime.now()
Year = str(stamp)[:4]
Month = str(stamp)[5:7]
Day = str(stamp)[8:10]
Hour = str(stamp)[11:13]
Minutes = str(stamp)[14:16]
Seconds = str(stamp)[17:18]
Date = Year + Month + Day
time = Hour + ':' + Minutes + ':' + Seconds

file = 'file.txt'
header_names = 't1':'Test1', 't2': 'Test2','t3':'Test3'
with open(file, 'w', newline='') as f:
f.seek(0,0)
f.writelines("Name: ", file)
f.writelines("Date: ",date)
f.writelines("Time: ",time)
w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='',
extrasaction='ignore')
w.writerow(header_names)
for doc in res['test']['test']:
my_dict = doc['test']
w.writerow(my_dict)
f.seek(0,2)
f.writelines("This is generated using Python")


Current file looks like below. - file.txt



header
Name:file.txt
Date:20190321
Time:9:15:00

data
Test1,Test2,Test3
Bob,john,Male
Cat,Long,female
Dog,Short,Male
Case,Fast,Male
Nice,who,Male


Ideal file output - file.txt



header
Name:file.txt
Date:20190321
Time:09:15:00
AddedTime:09:30:00

data
Test1,Test2,Test3
Bob,john,Male
Cat,Long,female
Dog,Short,Male
Case,Fast,Male
Nice,who,Male


any help will be appreciated.










share|improve this question






















  • Are you trying to retroactively add the line to existing files, or are you just trying to figure out how to add a timedelta to a datetime?

    – Craig Meier
    Mar 21 at 16:41













0












0








0








I have the below code where it is adds a header to my file. you can see in the header it adds; 'name', 'date' and 'time'.



what i am trying to attempted next is to add another line in the header called 'AddedTime'. this field needs to add 15 mins on top of the current time and output it out into the 'AddedTime' header.



Python code.



stamp = datetime.datetime.now()
Year = str(stamp)[:4]
Month = str(stamp)[5:7]
Day = str(stamp)[8:10]
Hour = str(stamp)[11:13]
Minutes = str(stamp)[14:16]
Seconds = str(stamp)[17:18]
Date = Year + Month + Day
time = Hour + ':' + Minutes + ':' + Seconds

file = 'file.txt'
header_names = 't1':'Test1', 't2': 'Test2','t3':'Test3'
with open(file, 'w', newline='') as f:
f.seek(0,0)
f.writelines("Name: ", file)
f.writelines("Date: ",date)
f.writelines("Time: ",time)
w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='',
extrasaction='ignore')
w.writerow(header_names)
for doc in res['test']['test']:
my_dict = doc['test']
w.writerow(my_dict)
f.seek(0,2)
f.writelines("This is generated using Python")


Current file looks like below. - file.txt



header
Name:file.txt
Date:20190321
Time:9:15:00

data
Test1,Test2,Test3
Bob,john,Male
Cat,Long,female
Dog,Short,Male
Case,Fast,Male
Nice,who,Male


Ideal file output - file.txt



header
Name:file.txt
Date:20190321
Time:09:15:00
AddedTime:09:30:00

data
Test1,Test2,Test3
Bob,john,Male
Cat,Long,female
Dog,Short,Male
Case,Fast,Male
Nice,who,Male


any help will be appreciated.










share|improve this question














I have the below code where it is adds a header to my file. you can see in the header it adds; 'name', 'date' and 'time'.



what i am trying to attempted next is to add another line in the header called 'AddedTime'. this field needs to add 15 mins on top of the current time and output it out into the 'AddedTime' header.



Python code.



stamp = datetime.datetime.now()
Year = str(stamp)[:4]
Month = str(stamp)[5:7]
Day = str(stamp)[8:10]
Hour = str(stamp)[11:13]
Minutes = str(stamp)[14:16]
Seconds = str(stamp)[17:18]
Date = Year + Month + Day
time = Hour + ':' + Minutes + ':' + Seconds

file = 'file.txt'
header_names = 't1':'Test1', 't2': 'Test2','t3':'Test3'
with open(file, 'w', newline='') as f:
f.seek(0,0)
f.writelines("Name: ", file)
f.writelines("Date: ",date)
f.writelines("Time: ",time)
w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='',
extrasaction='ignore')
w.writerow(header_names)
for doc in res['test']['test']:
my_dict = doc['test']
w.writerow(my_dict)
f.seek(0,2)
f.writelines("This is generated using Python")


Current file looks like below. - file.txt



header
Name:file.txt
Date:20190321
Time:9:15:00

data
Test1,Test2,Test3
Bob,john,Male
Cat,Long,female
Dog,Short,Male
Case,Fast,Male
Nice,who,Male


Ideal file output - file.txt



header
Name:file.txt
Date:20190321
Time:09:15:00
AddedTime:09:30:00

data
Test1,Test2,Test3
Bob,john,Male
Cat,Long,female
Dog,Short,Male
Case,Fast,Male
Nice,who,Male


any help will be appreciated.







python python-3.x






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 21 at 16:37









R.DaveR.Dave

14




14












  • Are you trying to retroactively add the line to existing files, or are you just trying to figure out how to add a timedelta to a datetime?

    – Craig Meier
    Mar 21 at 16:41

















  • Are you trying to retroactively add the line to existing files, or are you just trying to figure out how to add a timedelta to a datetime?

    – Craig Meier
    Mar 21 at 16:41
















Are you trying to retroactively add the line to existing files, or are you just trying to figure out how to add a timedelta to a datetime?

– Craig Meier
Mar 21 at 16:41





Are you trying to retroactively add the line to existing files, or are you just trying to figure out how to add a timedelta to a datetime?

– Craig Meier
Mar 21 at 16:41












2 Answers
2






active

oldest

votes


















0














import datetime
print(datetime.datetime.now() + datetime.timedelta(minutes=15))

2019-03-21 12:57:50.418277





share|improve this answer






























    0














    Yes it's quite simple with datetime.timedelta, just do an addition of 15 mins, and you could use strftime to format the datetime output.



    addedTime = (stamp + datetime.timedelta(minutes=15)).strftime('%H:%M:%S')





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285243%2fpython-adding-time-in-a-txt-file%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      import datetime
      print(datetime.datetime.now() + datetime.timedelta(minutes=15))

      2019-03-21 12:57:50.418277





      share|improve this answer



























        0














        import datetime
        print(datetime.datetime.now() + datetime.timedelta(minutes=15))

        2019-03-21 12:57:50.418277





        share|improve this answer

























          0












          0








          0







          import datetime
          print(datetime.datetime.now() + datetime.timedelta(minutes=15))

          2019-03-21 12:57:50.418277





          share|improve this answer













          import datetime
          print(datetime.datetime.now() + datetime.timedelta(minutes=15))

          2019-03-21 12:57:50.418277






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 21 at 16:43









          BMWBMW

          369213




          369213























              0














              Yes it's quite simple with datetime.timedelta, just do an addition of 15 mins, and you could use strftime to format the datetime output.



              addedTime = (stamp + datetime.timedelta(minutes=15)).strftime('%H:%M:%S')





              share|improve this answer



























                0














                Yes it's quite simple with datetime.timedelta, just do an addition of 15 mins, and you could use strftime to format the datetime output.



                addedTime = (stamp + datetime.timedelta(minutes=15)).strftime('%H:%M:%S')





                share|improve this answer

























                  0












                  0








                  0







                  Yes it's quite simple with datetime.timedelta, just do an addition of 15 mins, and you could use strftime to format the datetime output.



                  addedTime = (stamp + datetime.timedelta(minutes=15)).strftime('%H:%M:%S')





                  share|improve this answer













                  Yes it's quite simple with datetime.timedelta, just do an addition of 15 mins, and you could use strftime to format the datetime output.



                  addedTime = (stamp + datetime.timedelta(minutes=15)).strftime('%H:%M:%S')






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 21 at 16:44









                  Ian LoubserIan Loubser

                  1195




                  1195



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285243%2fpython-adding-time-in-a-txt-file%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript