I must have the current year and month in datetime.
I use this:
datem = datetime.today().strftime("%Y-%m")
datem = datetime.strptime(datem, "%Y-%m")
Is there maybe another way?
Try this solution:
from datetime import datetime
currentSecond= datetime.now().second
currentMinute = datetime.now().minute
currentHour = datetime.now().hour
currentDay = datetime.now().day
currentMonth = datetime.now().month
currentYear = datetime.now().year
Use:
from datetime import datetime
today = datetime.today()
datem = datetime(today.year, today.month, 1)
I assume you want the first of the month.
Use:
from datetime import datetime
current_month = datetime.now().strftime('%m') // 02 //This is 0 padded
current_month_text = datetime.now().strftime('%h') // Feb
current_month_text = datetime.now().strftime('%B') // February
current_day = datetime.now().strftime('%d') // 23 //This is also padded
current_day_text = datetime.now().strftime('%a') // Fri
current_day_full_text = datetime.now().strftime('%A') // Friday
current_weekday_day_of_today = datetime.now().strftime('%w') //5 Where 0 is Sunday and 6 is Saturday.
current_year_full = datetime.now().strftime('%Y') // 2018
current_year_short = datetime.now().strftime('%y') // 18 without century
current_second= datetime.now().strftime('%S') //53
current_minute = datetime.now().strftime('%M') //38
current_hour = datetime.now().strftime('%H') //16 like 4pm
current_hour = datetime.now().strftime('%I') // 04 pm
current_hour_am_pm = datetime.now().strftime('%p') // 4 pm
current_microseconds = datetime.now().strftime('%f') // 623596 Rarely we need.
current_timzone = datetime.now().strftime('%Z') // UTC, EST, CST etc. (empty string if the object is naive).
Reference: 8.1.7. strftime() and strptime() Behavior
Reference: strftime() and strptime() Behavior
The above things are useful for any date parsing, not only now or today. It can be useful for any date parsing.
e.g.
my_date = "23-02-2018 00:00:00"
datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S+00:00')
datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%m')
And so on...
>>> from datetime import date
>>> date.today().month
2
>>> date.today().year
2020
>>> date.today().day
13
The question asks to use datetime specifically.
This is a way that uses datetime only:
from datetime import datetime
year = datetime.now().year
month = datetime.now().month
Late answer, but you can also use:
import time
ym = time.strftime("%Y-%m")
You can write the accepted answer as a one-liner using date.replace:
datem = datetime.today().replace(day=1)
You can always use a sub-string method:
import datetime;
today = str(datetime.date.today());
curr_year = int(today[:4]);
curr_month = int(today[5:7]);
This will get you the current month and year in integer format. If you want them to be strings you simply have to remove the " int " precedence while assigning values to the variables curr_year and curr_month.
using the regular expression extract the date and time from the string then convert the string date to a datetimeindex using strptime
import re
s = "Audio was recorded at 21:50:00 02/07/2019 (UTC) by device 243B1F05 at gain setting 2 while battery state was 3.6V."
t = re.search(' (\d{2}:\d{2}:\d{2} \d{2}\/\d{2}\/\d{4}) ', s).group(1)
date=datetime.datetime.strptime(t,'%H:%M:%S %m/%d/%Y')
print(type(date))
Related
I'd like to get the break of a variable by year, month and day. Here's what I got:
import datetime
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
print (yesterday)
year = datetime.date.yesterday.year
month = datetime.date.yesterday.month
day=datetime.date.yesterday.day
print (year)
print (month)
print (day)
I'm getting an error that datetime.date has no attribute. I'm a total noob at python and I'm stuck, any help is appreciated
you were close
import datetime
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
print (yesterday)
year = yesterday.year
month = yesterday.month
day=yesterday.day
print (year)
print (month)
print (day)
result is
2019-03-10
2019
3
10
You can use strftime method
A simple example:
>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> year_month_day_format = '%Y-%m-%d'
>>> now.strftime(year_month_day_format)
'2020-11-06'
>>> hour_minute_format = '%H:%M'
>>> now.strftime(hour_minute_format)
'22:54'
Hopping, it will help someones
You can also simplify your import statements like so:
from datetime import datetime, timedelta
yesterday = datetime.today() - timedelta(1)
print(yesterday)
year = yesterday.year
month = yesterday.month
day = yesterday.day
print(year)
print(month)
print(day)
You will get the output:
2019-03-10 21:19:36.695577
2019
3
10
For current day
import datetime
current_datetime=datetime.datetime.now()
print("current_year:{}".format(current_datetime.year))
print("current_month:{}".format(current_datetime.month))
print("current_day:{}".format(current_datetime.day))
If you want in this format for example "10-Oct-2018". You can try this code for current day.
from datetime import datetime, timezone
now_utc = datetime.now(timezone.utc)
year = now_utc.strftime("%Y")
month = now_utc.strftime("%b")
day = now_utc.strftime("%d")
result = day+"-"+month+"-"+year
print(result)
I am making a program where I input start date to dataStart(example 21.10.2000) and then input int days dateEnd and I convert it to another date (example 3000 = 0008-02-20)... Now I need to count these dates together, but I didn't managed myself how to do that. Here is my code.
from datetime import date
start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))
dataStart=start.split(".")
days=int(dataStart[0])
months=int(dataStart[1])
years=int(dataStart[2])
endYears=0
endMonths=0
endDays=0
dateStart = date(years, months, days)
while end>=365:
end-=365
endYears+=1
else:
while end>=30:
end-=30
endMonths+=1
else:
while end>=1:
end-=1
endDays+=1
dateEnd = date(endYears, endMonths, endDays)
For adding days into date, you need to user datetime.timedelta
start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))
date = datetime.strptime(start, "%d.%m.%Y")
modified_date = date + timedelta(days=end)
print(datetime.strftime(modified_date, "%d.%m.%Y"))
You may use datetime.timedelta to add certain units of time to your datetime object.
See the answers here for code snippets: Adding 5 days to a date in Python
Alternatively, you may wish to use the third-party dateutil library if you need support for time additions in units larger than weeks. For example:
>>> from datetime import datetime
>>> from dateutil import relativedelta
>>> one_month_later = datetime(2017, 5, 1) + relativedelta.relativedelta(months=1)
>>> one_month_later
>>> datetime.datetime(2017, 6, 1, 0, 0)
It will be easier to convert to datetime using datetime.datetime.strptime and for the part about adding days just use datetime.timedelta.
Below is a small snippet on how to use it:
import datetime
start = "21.10.2000"
end = 8
dateStart = datetime.datetime.strptime(start, "%d.%m.%Y")
dateEnd = dateStart + datetime.timedelta(days=end)
dateEnd.date() # to get the date format of the endDate
If you have any doubts please look at the documentation python3/python2.
I have spent some time trying to figure out how to get a time delta between time values. The only issue is that one of the times was stored in a file. So I have one string which is in essence str(datetime.datetime.now()) and datetime.datetime.now().
Specifically, I am having issues getting a delta because one of the objects is a datetime object and the other is a string.
I think the answer is that I need to get the string back in a datetime object for the delta to work.
I have looked at some of the other Stack Overflow questions relating to this including the following:
Python - Date & Time Comparison using timestamps, timedelta
Comparing a time delta in python
Convert string into datetime.time object
Converting string into datetime
Example code is as follows:
f = open('date.txt', 'r+')
line = f.readline()
date = line[:26]
now = datetime.datetime.now()
then = time.strptime(date)
delta = now - then # This does not work
Can anyone tell me where I am going wrong?
For reference, the first 26 characters are acquired from the first line of the file because this is how I am storing time e.g.
f.write(str(datetime.datetime.now())
Which would write the following:
2014-01-05 13:09:42.348000
time.strptime returns a struct_time.
datetime.datetime.now() returns a datetime object.
The two can not be subtracted directly.
Instead of time.strptime you could use datetime.datetime.strptime, which returns a datetime object. Then you could subtract now and then.
For example,
import datetime as DT
now = DT.datetime.now()
then = DT.datetime.strptime('2014-1-2', '%Y-%m-%d')
delta = now - then
print(delta)
# 3 days, 8:17:14.428035
By the way, you need to supply a date format string to time.strptime or DT.datetime.strptime.
time.strptime(date)
should have raised a ValueError.
It looks like your date string is 26 characters long. That might mean you have a date string like 'Fri, 10 Jun 2011 11:04:17 '.
If that is true, you may want to parse it like this:
then = DT.datetime.strptime('Fri, 10 Jun 2011 11:04:17 '.strip(), "%a, %d %b %Y %H:%M:%S")
print(then)
# 2011-06-10 11:04:17
There is a table describing the available directives (like %Y, %m, etc.) here.
Try this:
import time
import datetime
d = datetime.datetime.now()
now = time.mktime(d.timetuple())
And then apply the delta
if you have the year,month,day of 'then' you may use:
year = 2013
month = 1
day = 1
now_date = datetime.datetime.now()
then_date = now_date.replace(year = year, month = month, day = day)
delta = now_date - then_date
I need to parse strings representing 6-digit dates in the format yymmdd where yy ranges from 59 to 05 (1959 to 2005). According to the time module docs, Python's default pivot year is 1969 which won't work for me.
Is there an easy way to override the pivot year, or can you suggest some other solution? I am using Python 2.7. Thanks!
I'd use datetime and parse it out normally. Then I'd use datetime.datetime.replace on the object if it is past your ceiling date -- Adjusting it back 100 yrs.:
import datetime
dd = datetime.datetime.strptime(date,'%y%m%d')
if dd.year > 2005:
dd = dd.replace(year=dd.year-100)
Prepend the century to your date using your own pivot:
year = int(date[0:2])
if 59 <= year <= 99:
date = '19' + date
else
date = '20' + date
and then use strptime with the %Y directive instead of %y.
import datetime
date = '20-Apr-53'
dt = datetime.datetime.strptime( date, '%d-%b-%y' )
if dt.year > 2000:
dt = dt.replace( year=dt.year-100 )
^2053 ^1953
print dt.strftime( '%Y-%m-%d' )
You can also perform the following:
today=datetime.datetime.today().strftime("%m/%d/%Y")
today=today[:-4]+today[-2:]
Recently had a similar case, ended up with this basic calculation and logic:
pivotyear = 1969
century = int(str(pivotyear)[:2]) * 100
def year_2to4_digit(year):
return century + year if century + year > pivotyear else (century + 100) + year
If you are dealing with very recent dates as well as very old dates and want to use the current date as a pivot (not just the current year), try this code:
import datetime
def parse_date(date_str):
parsed = datetime.datetime.strptime(date_str,'%y%m%d')
current_date = datetime.datetime.now()
if parsed > current_date:
parsed = parsed.replace(year=parsed.year - 100)
return parsed
i know using datetime.timedelta i can get the date of some days away form given date
daysafter = datetime.date.today() + datetime.timedelta(days=5)
but seems no datetime.timedelta(month=1)
Use dateutil module. It has relative time deltas:
import datetime
from dateutil import relativedelta
nextmonth = datetime.date.today() + relativedelta.relativedelta(months=1)
Beautiful.
Of course there isn't -- if today's January 31, what would be "the same day of the next month"?! Obviously there is no right solution, since February 31 does not exist, and the datetime module does not play at "guess what the user posing this impossible problem without a right solution thinks (wrongly) is the obvious solution";-).
I suggest:
try:
nextmonthdate = x.replace(month=x.month+1)
except ValueError:
if x.month == 12:
nextmonthdate = x.replace(year=x.year+1, month=1)
else:
# next month is too short to have "same date"
# pick your own heuristic, or re-raise the exception:
raise
You can use calendar.nextmonth (from Python 3.7).
>>> import calendar
>>> calendar.nextmonth(year=2019, month=6)
(2019, 7)
>>> calendar.nextmonth(year=2019, month=12)
(2020, 1)
But be aware that this function isn't meant to be public API, it's used internally in calendar.Calendar.itermonthdays3() method. That's why it doesn't check the given month value:
>>> calendar.nextmonth(year=2019, month=60)
(2019, 61)
In Python 3.8 is already implemented as internal function.
from calendar import mdays
from datetime import datetime, timedelta
today = datetime.now()
next_month_of_today = today + timedelta(mdays[today.month])
I don't want to import dateutil. Have a try this. Good luck.
import calendar, datetime
def next_month ( date ):
"""return a date one month in advance of 'date'.
If the next month has fewer days then the current date's month, this will return an
early date in the following month."""
return date + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1])
This work for me
import datetime
import calendar
def next_month_date(d):
_year = d.year+(d.month//12)
_month = 1 if (d.month//12) else d.month + 1
next_month_len = calendar.monthrange(_year,_month)[1]
next_month = d
if d.day > next_month_len:
next_month = next_month.replace(day=next_month_len)
next_month = next_month.replace(year=_year, month=_month)
return next_month
usage:
d = datetime.datetime.today()
print next_month_date(d)
This is how I solved it.
from datetime import datetime, timedelta
from calendar import monthrange
today_date = datetime.now().date() # 2021-10-29
year = today_date.year
month = today_date.month
days_in_month = monthrange(year, month)[1]
next_month = today_date + timedelta(days=days_in_month)
print(next_month) # 2021-11-29
Solution on Python3 without additional modules nor internal functions.
from datetime import date
today = date.today()
nextMonth = date(today.year+((today.month+1)//12) , ((today.month+1)%12), today.day)
Hurray for integer algebra!
from datetime import timedelta
try:
next_month = (x.replace(day=28) + timedelta(days=7)).replace(day=x.day)
except ValueError: # assuming January 31 should return last day of February.
next_month = (x + timedelta(days=31)).replace(day=1) - timedelta(days=1)
from dateutil.relativedelta import relativedelta
from dateutil import parser
d2 = "1/4/2022 8:39:23 AM"
NextMonth = parser.parse(d2) + relativedelta(months=+1) + relativedelta(days=-1)
print(NextMonth)
This is how I solved it.
from datetime import date
try:
(year, month) = divmod(date.today().month, 12)
next_month = date.today().replace(year=date.today().year+year, month=month+1)
except ValueError:
# This day does not exist in next month
You can skip the try/catch if you only want the first day in next month by setting replace(year=date.today().year+year, month=month, day=1). This will always be a valid date since we have caught the month overflow using divmod.
I often need to need to keep the date as last in month when adding months. I try to add the amount of months to the day after and then remove one day again. If that fails I add one more day until success.
from datetime import timedelta
DAY = timedelta(1)
def add_months(d, months):
"Add months to date and retain last day in month."
d += DAY
# calculate year diff and zero based month
y, m = divmod(d.month + months - 1, 12)
try:
return d.replace(d.year + y, m + 1) - DAY
except ValueError:
# on fail return last day in month
# can't fail on december so just adding one more month
return d.replace(d.year + y, m + 2, 1) - DAY
This Code Works for me:
NextMonth = self.CurruntMonth.replace(day=15) + datetime.timedelta(days=30)