Python: How to find the current date

Asked

Viewed 119 times

-2

I am trying to fetch some files from a folder that brings a pattern in the file name, in case it is 3067-EG3067000076 plus the date, but as they will be daily files the date changes daily and there is also another however, as the date when I download the file comes from the previous day I need to go back one day (so day=1) and when the file is downloaded on Monday I need to go back 3 days so the (days=3) thinking about these variants I developed this code, At first it worked but now it doesn’t work anymore, would anyone have a suggestion of which function to use for the date? or a code suggestion?

import os
import calendar
from datetime import date
from pathlib import Path

data_atual = calendar.day_name[my_date.weekday()]
    
if data_atual == 'Monday':
    teste= 'true'
else: 
    teste= 'false'

if teste == 'true':
    data_atual = datetime.datetime.now() - datetime.timedelta(days=3)
    data_atual = (data_atual.strftime("%Y%m%d"))
else:
    data_atual = datetime.datetime.now() - datetime.timedelta(days=1)
    data_atual = (data_atual.strftime("%Y%m%d"))
    
os.rename(r'C:\Users\joao\Desktop\convenios\3067-EG3067000076' + str(data_atual) + '.CNV',r'C:\Users\joao\Desktop\convenios2\arquivo.CNV')

The code generates this error:

Nameerror Traceback (Most recent call last) in 4 from pathlib import Path 5 ----> 6 current date = Calendar.day_name[my_date.weekday()] 7 8 if currentdata_== 'Monday': Nameerror: name 'my_date' is not defined

  • What is the result obtained?

  • The first time I tested it worked, now it presents this error. --------------------------------------------------------------------------- Nameerror Traceback (Most recent call last) <ipython-input-1-dae84386bf9f> in <module> 4 from pathlib import Path 5 ---> 6 currentdata_ = Calendar.day_name[my_date.weekday()] 7 8 if currentdata_='Monday': Nameerror: name 'my_date' is not defined

3 answers

2

Your logic is correct, but there are strange things in your code.

data_atual = calendar.day_name[my_date.weekday()]
    
if data_atual == 'Monday':
    teste= 'true'
else: 
    teste= 'false'
  1. In the first line of the code snippet, you do my_date.weekday(), but the object my_date It was never defined, causing the mistake you quoted in the comments. You commented that "the first time worked", but it was probably another code. This will never work [except if there is code before that you didn’t ask the question].

  2. There’s no point in you doing it teste = 'true'. One that the variable name teste is terrible and does not refer to anything that the variable represents. According to Python there is the boolean type for these cases, represented by values True and False. There’s no reason to create a string for this.

In short, what you need is always take the last working day, so you can simplify the code:

import datetime


def get_last_business_day():
    today = datetime.date.today()
    delta = max(1, (today.weekday() + 6) % 7 - 3)
    return today - datetime.timedelta(days=delta)

For didactic purposes, we will call the value within max, (today.weekday() + 6) % 7 - 3, of x, and then assemble the following table relating the value of today.weekday(), which refers to which day of the week we are worth x:

Day today.weekday() x max(1, x)
Monday 0 3 3
Tuesday 1 -3 1
Wednesday 2 -2 1
Thursday 3 -1 1
Friday 4 0 1
Saturday 5 1 1
Domingo 6 2 2

Note: important to note that even though in our calendar the week starts on Sunday, in Python the zero day is the Monday as an option of the creators of the library simply to facilitate the verification whether it is a working day or not (day.weekday() < 5)

Thus we see that if it is a Monday, we will deduct 3 days to get the last Friday; if it is Sunday, it will be 2 days; if it is Saturday, a day; and if it is any other day, a day also.

  • woss good night, first I want to thank you for the help, I understood your code but when I run in my jupyter it does not return anything, even giving print. I tried to format the date to %Y%m%d" and returns nothing

  • @Gabrielterribile you called the function?

  • It worked Woss, thank you very much!

0

From what I understand, you want to do something like:

import datetime  
import calendar

dataHoje = datetime.datetime.now() #define a data de hoje
diaHoje = (calendar.day_name[dataHoje.weekday()]) #define o dia hoje
print("data: ", dataHoje,"\ndia semana: ", diaHoje ) #apresenta os resultados

x = int(input("Dias a retirar: ")) #escolher dias a voltar atrás

data = datetime.timedelta(days = x) #define os -x dias em formato data
finalData = dataHoje - data #define a data -x
finalDia = calendar.day_name[finalData.weekday()] #define o dia -x
print ("Data: ", finalData, "\nDia: ", finalDia) #Apresenta o resultado

This will show you the date and day, just change the input from "x" to your variable that takes the days. Now, to make the "if" just do the following:

if (finalDia == "Friday"):
    #Faz aqui o que quiser

Note: The program takes away my days in English, you have to change the "if" based on what you take out on your computer.

-1

From what I could see you are trying to change the name of the file according to date of the day, this can be done through the library datetime, gets my recommendation from reading because with this library it returns date day hours seconds everything you need for your code.

follows an example of how to get the date and include in the file.

makedirs(r'\Solicitações dia {}'.format(datetime.now().strftime('%d-%m-%y')))

if you need more information on the link left above there is a table with parameters to be passed in the function.

now to go back the days the return of the above code is a string so you should convert and maybe create a function that goes back the days you need:

maybe this code below can help in developing the logic for your application:

from datetime import datetime

data = datetime.now().strftime('%H:%M - %A %d / %B / %Y')


def escrever_datas_por_extenso(data):

    mesesEN =['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
              'November', 'December']

    mesesPT = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro',
               'Novembro', 'Dezembro']

    diasPT = ['Segunda-Feira', 'Terça-Feira', 'Quarta-feira', 'Quinta-Feira', 'Sexta-feira', 'Sabado', 'Domingo']

    diasEN = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

datalist = data.split()

datalist[2] = diasPT[diasEN.index(datalist[2])]

datalist[5] = mesesPT[mesesEN.index(datalist[5])]

data = ''

for palavra in datalist:
    data = data + " " + palavra

return data

print(escrever_datas_por_extenso(data))

and to return the dates just create a condition that works the index of the date you want

  • All right, Kelvin, that’s the idea, thanks for your help!

  • @Gabrielterribile if any of the answers answered your request, it is a good custom to mark as correct for people who have the same doubt know which solved your problem.

  • Show, the 3 in a way contributed so I scored the 3 :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.