Python Forum
Logic to convert an integer to YEAR / MONTH
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Logic to convert an integer to YEAR / MONTH
#1
Lógica para converter um número inteiro para ANO/MÊS

Pessoal, Boa tarde.
Preciso de uma ajuda. Minha dúvida nem é na sintaxe em si, mas em lógica mesmo. Sozinho não to conseguindo resolver.
Preciso criar Arquivos com nome ("DC" + anoAtual + Mes). ex: DC201610, somar 1 ano se passar do mês 12 e ir incrementando o mês até 12
O usuário entra com 2 entradas.
  1. Número de meses para gerar

  2. Mes de inicio de 1..12
Eu já to gerando os arquivos, e criando os nomes. Mas só funciona se o usuario de o mês de inicio o mês 01 = Janeiro. porque ele vai até 12 e volta para 01.
O problema está se o usuário começa no mês 10 e precisa criar 5 meses(Arquivos) por exemplo.
Como deveria ficar: DC201610       Como ele está criando: DC201610
                                DC201611                                            DC201611
                                DC201612                                            DC201612
                                DC201701                                            DC201613
                                DC201702                                            DC201614

Alguém pode me ajudar?  :wall:


Translation
Staff, Good afternoon.
I need help. My question is not in the syntax itself, but even in logic. Alone not getting to solve.
I need to create files with the name ("DC" + anoAtual + Mes). eg DC201610, add one year to spend the month 12 and go up to 12 incrementing the month
The user enters 2 entries.

  1. Number of months to generate
  2. Start Month 1..12

I have to generate the files, and creating names. But it only works if the User of the beginning of the month month = January 01. because it goes to 12 and back to 01.
The problem is if the user begins the month 10 and need to create five months (Files) for example.

As it should be:
Output:
DC201610 DC201611 DC201612 DC201701 DC201702
as it is creating:
Output:
DC201610 DC201611 DC201612 DC201613 DC201614
Can someone help me?  :wall:
Reply
#2
It would help greatly if your post were in English. The only thing I understood was  :wall:
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#3
<Moved to coding help.>

Code in the post would be nice too.
Reply
#4
Windows, Max OS X or Linux?
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
We're not going to do your work for you: what have you tried?
Reply
#6
Please post the code that you have so far.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#7
Hi Guys,

Thanks to answers, i'm using Windows OS.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Autor: Hugo Baur [email protected]

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os.path
import shutil
from datetime import date
now = date.today()

#FILENAME = "E:/ENEL/Modelos/DC201609/DC201609-sem1/DADGER.rv0"
WORD = "& NO. SEMANAS NO MES INIC. DO ESTUDO=> 5"
#-------------------------FUNÇÕES--------------------------------

def criarPastaDestino():  # FUNÇÃO PARA CRIAR A PASTA RECIPIENTE , CRIAR AS SUB PASTAS E COPIAR SEU CONTEUDO
   os.mkdir(directoryPath)
   for x in range(0, int(meses)):
       if x <= 9:
           aux = (directoryPath + "DC" + str(now.year) + "0" + str(int(iniMes) + x) + "/")
       # os.mkdir(aux)
       numeroSemanas = find_word_in_file(origem + "/DADGER.rv0", WORD)
       teste = numeroSemanas.replace('& NO. SEMANAS NO MES INIC. DO ESTUDO=> ', '')
       if x < 1:
           os.mkdir(aux)
           for i in range(1, int(teste)-2):
               a =str(x)
               b = str(i)
               #os.mkdir (aux + "DC" + str(now.year) + str(int(iniMes)) + "-sem" + b)
               #os.mkdir (aux + "Relatorio_Sumario-" + "DC" + str(now.year) + str(int(iniMes))+ "-sem" + b)
               if x <= 9:
                   criarpastas = (aux + "DC" + str(now.year) + "0" + str(int(iniMes) + x) + "-sem" + b)
                   criarpastasrelatorio = (aux + "Relatorio_Sumario-" + "DC" + str(now.year) + "0" + str(int(iniMes) + x) + "-sem" + b)
               else:
                   criarpastas = (aux + "DC" + str(now.year) + str(int(iniMes) + x) + "-sem" + b)
                   criarpastasrelatorio = (aux + "Relatorio_Sumario-" + "DC" + str(now.year) + str(int(iniMes) + x) + "-sem" + b)
               shutil.copytree(origem, criarpastas  + "/")
               shutil.copytree(origem, criarpastasrelatorio  + "/")

               # ALTERAR EXTENSÃO DE ARQUIVOS
               os.rename(criarpastas + "/"+ "DADGNL.RV0", criarpastas + "/"+ "DADGNL.RV" + str(i-1))
               os.rename(criarpastas + "/"+ "DADGER.RV0", criarpastas + "/"+ "DADGER.RV" + str(i-1))
               os.rename(criarpastas + "/"+ "PREVS.RV0", criarpastas + "/"+ "PREVS.RV" + str(i-1))
               os.rename(criarpastas + "/"+ "RV0.dat", criarpastas + "/"+ "RV" + str(i-1) +".dat")
               os.rename(criarpastas + "/"+ "VAZOES.RV0", criarpastas + "/"+ "VAZOES.RV" + str(i-1))

               os.rename(criarpastasrelatorio + "/"+"DADGNL.RV0", criarpastasrelatorio + "/"+ "DADGNL.RV" + str(i-1))
               os.rename(criarpastasrelatorio + "/"+"DADGER.RV0", criarpastasrelatorio + "/"+ "DADGER.RV" + str(i-1))
               os.rename(criarpastasrelatorio + "/"+"PREVS.RV0", criarpastasrelatorio + "/"+ "PREVS.RV" + str(i-1))
               os.rename(criarpastasrelatorio + "/"+"RV0.dat", criarpastasrelatorio + "/"+ "RV" + str(i-1) +".dat")
               os.rename(criarpastasrelatorio + "/"+ "VAZOES.RV0", criarpastasrelatorio + "/"+ "VAZOES.RV" + str(i-1))
           # E:/ENEL/Modelos/DC201609/DC201609-sem1
           # C:/TESTESISTEMA
           # E:/ENEL/Modelos/NW201610
       else:
           if (int(iniMes) + x) <= 9: #8 9 12
               aux = (directoryPath + "DC" + str(now.year) + "0" + str(int(iniMes) + x) + "/")
           else:
               if (int(iniMes) + x) > 9 and x < 12:
                   aux = (directoryPath + "DC" + str(now.year) + str(int(iniMes) + x) + "/")
               else:
                   if (int(iniMes) + x) >= 12 and x < 21:
                       aux = (directoryPath + "DC" + str(now.year + 1) + "0" + str(int(iniMes) + x - 12) + "/")
                   else:
                       if (int(iniMes) + x) >= 21 and x < 24:
                           aux = (directoryPath + "DC" + str(now.year + 1) + str(int(iniMes) + x - 12) + "/")
                       else:
                           if (int(iniMes) + x) >= 24 and x < 33:
                               aux = (directoryPath + "DC" + str(now.year + 2) + "0" + str(int(iniMes) + x - 24) + "/")
                           else:
                               if (int(iniMes) + x) >= 33 and x < 36:
                                   aux = (directoryPath + "DC" + str(now.year + 2) + str(int(iniMes) + x - 24) + "/")
                               else:
                                   if (int(iniMes) + x) >= 36 and x < 45:
                                       aux = (directoryPath + "DC" + str(now.year + 3) + "0" + str(int(iniMes) + x - 36) + "/")
                                   else:
                                       if (int(iniMes) + x) >= 45 and x < 48:
                                           aux = (directoryPath + "DC" + str(now.year + 3) + str(int(iniMes) + x - 36) + "/")
                                       else:
                                           if (int(iniMes) + x) >= 48 and x < 57: #44 45 48
                                               aux = (directoryPath + "DC" + str(now.year + 4) + "0" + str(int(iniMes) + x - 48) + "/")
                                           else:
                                                if (int(iniMes) + x) >= 57 and x < 60: #56 57 60
                                                   aux = (directoryPath + "DC" + str(now.year + 4) + str(int(iniMes) + x - 48) + "/")
           shutil.copytree(origem, aux + "/")

# FUNÇÃO LOCALIZA A STRING "& NO. SEMANAS NO MES INIC. DO ESTUDO=> 5" E RETORNA O NUEMRO DE SEMANAS

def find_word_in_file(FILENAME, WORD):
   f = open(FILENAME, "r")
   file_array = f.readlines()
   f.close()
   for i in file_array:
       if i.find(WORD) >= 0:
           print("Localizado a string: " + i)
           return i
   return False

def newave_creator():
   if int(now.month) <= 9:
       path = (destino + "/" + "NW" + str(now.year) + "0" + str(int(now.month)) + "/")
   else:
       path = (destino + "/" + "NW" + str(now.year) + str(int(now.month)) + "/")
   shutil.copytree(origemNewave, path)
   print ("\n\n### Arquivos NEWAVE criados com sucesso! ###\n")


#-------------------------MENU-----------------------------------
digito = True
while digito:
   print("""
   1.Gerar dados para o modelo DCOMP
   2.Gerar dados para o modelo NEWAVE
   3.Opção 3
   4.Exit/Quit
   """)
   digito = input("O que gostaria de fazer? ")
   if digito == "1":
       print("\nModelo DECOMP")
       origem = input("Digite o caminho da ORIGEM dos dados: ") # DEFINE O PATH ORIGEM
       nomedapasta = input("Digite o nome da pasta que será criada: ") # DEFINE O NOME DA PASTA A SER CRIADA
       destino = input("Digite o caminho DESTINO dos dados: ") # DEFINE O PATH DE DESTINO
       meses = input("Digite o numero de meses: ") # RECEBE O NUMERO DE MESES DE ESTUDO
       iniMes = input("Digite o mês de início: ")  # RECEBE O INICIO DE MESES DE ESTUDO
       directoryPath = (destino + "/" + nomedapasta + "/")  # PEGAR O DESTINO E CONCATENAR COM O NOME ESCOLHIDO DA PASTA PELO USUÁRIO
       print("\n Você inseriu o caminho ORIGEM: " + origem + " e caminho DESTINO: " + directoryPath) # INFORMA AO USUÁRIO O PATH ORIGEM E O DESTINO
       criarPastaDestino()

       print("\n\n ## CRIAÇÃO BEM SUCEDIDA ##\n")
       print("__________________________________________________________________")

   elif digito == "2":
     print("\nModelo NEWAVE")
     origemNewave = input("Digite o caminho da ORIGEM dos dados: ")  # DEFINE O PATH ORIGEM
     destino = input("Digite o caminho DESTINO dos dados: ")  # DEFINE O PATH DE DESTINO
     newave_creator()

     print ("__________________________________________________________________")
   elif digito == "3":
       path = input("Digite o caminho da ORIGEM dos dados: ")  # DEFINE O PATH ORIGEM
       numeroSemanas = find_word_in_file(path + "/DADGER.rv0", WORD)
       teste = numeroSemanas.replace('& NO. SEMANAS NO MES INIC. DO ESTUDO=> ', '')
       print("Número de semanas lido: " + teste + "O número de semanas que será criado: " + str(int(teste) - 2))
   elif digito == "4":
     print("\n### OBRIGADO, TENHA UM BOM DIA! ###")
     digito = None
   else:
      print("\n#### Digito inválido, por favor digite um dos números do menu. ###")

So, to replices that, you need archives .txt, just 2.

one with the name "DADGER.rv0" containing the string "& NO. SEMANAS NO MES INIC. DO ESTUDO=> 5" and another with any name and any content, only for viewing.

First - Put de path od the first archive
Second - Name of the new archive
third - Path where the new files will be created
fourth - Number of the months
fifth - Number of the initial month

If you start using a initial month, its ok. Works!
if you start with the month 10 for example, doesn't work.
Reply
#8
I have no desire to read through all that, but it looks like you've got two values, year and month, and you're incrementing the month.  You could check to see if the new value is over 12 and reset it to 1...
>>> dates = []
>>> year = 2016
>>> month = 1
>>> for i in range(20):
...   dates.append('{0:04d}{1:02d}'.format(year, month))
...   month += 1
...   if month > 12:
...     month = 1
...     year += 1
...
>>> dates
['201601', '201602', '201603', '201604', '201605', '201606', '201607', '201608', '201609', '201610', '201611', '201612', '201701', '201702', '201703', '201704', '201705', '201706', '201707', '201708']
>>>
Then there's also the datetime module and friends in case you don't want to do that math yourself.
Reply
#9
This is what I came up with.
from datetime import date

def yield_file_dates(start_year, start_month, amount_of_months):
    current_date = date(start_year, start_month, 1)
    for _ in range(amount_of_months):
        yield 'DC{:%Y%m}'.format(current_date)
        if current_date.month == 12:
            current_date = current_date.replace(current_date.year + 1, 1)
        else:
            current_date = current_date.replace(month=current_date.month + 1)

for file_date in yield_file_dates(2016, 10, 5):
    print(file_date)
Output:
DC201610 DC201611 DC201612 DC201701 DC201702
Reply
#10
Yes!!!! WORKS!

Thanks to help me  Big Grin 

I really appreciate that!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  get list of dates in past month, current and upcoming month jacksfrustration 4 474 Feb-03-2024, 06:37 PM
Last Post: deanhystad
  Trying to get year not the entire year & time mbrown009 2 862 Jan-09-2023, 01:46 PM
Last Post: snippsat
  Python Resampling: How do I obtain the value of the last week of the month? JaneTan 2 971 Dec-12-2022, 12:49 AM
Last Post: JaneTan
  How to convert 4 bytes to an integer ? GiggsB 11 6,592 Jan-20-2022, 03:37 AM
Last Post: GiggsB
  Appropriate data-structure / design for business-day relations (week/month-wise) sx999 2 2,750 Apr-23-2021, 08:09 AM
Last Post: sx999
  Search Results Web results Printing the number of days in a given month and year afefDXCTN 1 2,190 Aug-21-2020, 12:20 PM
Last Post: DeaD_EyE
  Help with implementation of the logic to convert roman numeral to integer jagasrik 2 2,253 Aug-14-2020, 07:31 PM
Last Post: deanhystad
  Learning Python in a month MuhammadNauman 1 1,722 Jul-17-2019, 11:53 AM
Last Post: metulburr
  How to get all the data for the current month in ms Access using python? aeo03 1 2,282 Nov-07-2018, 08:21 PM
Last Post: micseydel
Question [Help] Convert integer to Roman numerals? {Screenshot attached} vanicci 10 9,042 Aug-06-2018, 05:19 PM
Last Post: vanicci

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020