This question already has answers here:
How do I calculate the date six months from the current date using the datetime Python module?
(47 answers)
Closed 3 years ago.
How do I remove 3 months from the date? tried to use relativedelta, but I don't have the lib, so is there another way?
from datetime import datetime
now = datetime.now()
print("timestamp =", now)
You can use:
import datetime
a = datetime.datetime.now()
b = a - datetime.timedelta(weeks=12)
Note that you cannot give months as inputs, but weeks and days, and smaller
Perhaps, subtracting with datetime.timedelta can help you estimate the date:
import datetime
datetime.datetime(2019,5,31) - datetime.timedelta(3*365.25/12)
This result is not completely accurate, as it does not account for the leap years in the usual way, however for less precise calculations within a year should suffice. If you need accuracy you will need to use the method below.
For dateutil.relativedelta, you need to first install the module with pip install python-dateutil, and then use it in the following way:
import datetime
from dateutil.relativedelta import relativedelta
datetime.datetime(2019,5,31) - relativedelta(months=3)
If you want to perform complex operations on datetime objects, I can only recommend you to use the library arrow that will handle all the edge cases for you.
The documentation of this library is available here: https://arrow.readthedocs.io/en/latest/
For instance in your case:
>>> import arrow
>>> a = arrow.utcnow()
>>> a
<Arrow [2019-11-20T13:03:52.518238+00:00]>
>>> a.datetime
datetime.datetime(2019, 11, 20, 13, 3, 52, 518238, tzinfo=tzutc())
>>> b = a.shift(months=-3)
>>> b
<Arrow [2019-08-20T13:03:52.518238+00:00]>
>>> b.datetime
datetime.datetime(2019, 8, 20, 13, 3, 52, 518238, tzinfo=tzutc())
Related
This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 1 year ago.
I'm parsing timestamp of event in a log record – 2020-08-09T03:37:33.358874554Z.
It looks strange to me and I don't know how correct is it. I don'think that 358874554 describe.
I'm trying to parse this example from Python 3.7 like this:
dt.datetime.strptime('2020-08-09T03:37:33.358874554Z', "%Y-%m-%dT%H:%M:%S.%fZ")
It generates an error:
ValueError: time data '2020-08-09T03:37:33.358874554Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'
How to parse such a datetime correctly?
Is this datetime example in log is correct (in terms of ISO or anything)?
You can use the dateutil.parser
Like this:
>>>>import dateutil.parser as p
>>>>p.parse('2020-08-09T03:37:33.358874554Z')
datetime.datetime(2020, 8, 9, 3, 37, 33, 358874, tzinfo=tzutc())
You should use dateutil module as an alternative:
$ pip install python-dateutil
>>> import dateutil.parser
>>> dateutil.parser.isoparse('2020-08-09T03:37:33.358874554Z')
datetime.datetime(2020, 8, 9, 3, 37, 33, 358874, tzinfo=tzutc())
This question already has answers here:
How do I get a value of datetime.today() in Python that is "timezone aware"?
(19 answers)
Closed 4 years ago.
My timezone is not UTC. When I get the date time with datetime.now() I get the local time, but the tzinfo field has the value none.
I see the same result with python 2.7 and python 3.6.7.
I would expect to get a timezone info or a time offset value. Why is that ? Is there a way to get the time offset as needed for the ISO time format ?
This is because now will get the present time of any particular timezone, by default it will give you the datetime object of current timezone that you're in (or your computer is set to).
You can get the present time of any other timezone, by passing that timezone to now function.
In [1]: from datetime import datetime
In [2]: import pytz # 3rd party: $ pip install pytz
In [4]: datetime.now()
Out[4]: datetime.datetime(2019, 2, 12, 20, 10, 2, 778532)
In [5]: datetime.now(pytz.utc)
Out[5]: datetime.datetime(2019, 2, 12, 14, 40, 4, 334078, tzinfo=<UTC>)
This question already has answers here:
How to truncate the time on a datetime object?
(18 answers)
How to display locale sensitive time format without seconds in python
(4 answers)
Closed 4 years ago.
I have a python datetime object that I want to display on a website, however the time shows in the format hh:mm:ss and I want to display it in the format hh:mm.
I have tried using the replace method as per the following:
message.timestamp.replace(second='0', microsecond=0)
However this doesn't get red of the seconds it just replaces it with hh:mm:00
Use strftime() function
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2018, 12, 27, 11, 14, 37, 137010)
>>> now = datetime.now()
>>> now.strftime("%H:%M")
'11:15'
Is there a nicer way than the following to return today's date in the YYYY-MM-DD format?
str(datetime.datetime.today()).split()[0]
Use strftime:
>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'
To also include a zero-padded Hour:Minute:Second at the end:
>>> datetime.today().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-26 16:50:03'
To get the UTC date and time:
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-27 00:50:03'
You can use datetime.date.today() and convert the resulting datetime.date object to a string:
from datetime import date
today = str(date.today())
print(today) # '2017-12-26'
I always use the isoformat() method for this.
from datetime import date
today = date.today().isoformat()
print(today) # '2018-12-05'
Note that this also works on datetime objects if you need the time in the standard ISO 8601 format as well.
from datetime import datetime
now = datetime.today().isoformat()
print(now) # '2018-12-05T11:15:55.126382'
Very late answer, but you can simply use:
import time
today = time.strftime("%Y-%m-%d")
# 2023-02-08
Datetime is just lovely if you like remembering funny codes. Wouldn't you prefer simplicity?
>>> import arrow
>>> arrow.now().format('YYYY-MM-DD')
'2017-02-17'
This module is clever enough to understand what you mean.
Just do pip install arrow.
Addendum: In answer to those who become exercised over this answer let me just say that arrow represents one of the alternative approaches to dealing with dates in Python. That's mostly what I meant to suggest.
Are you working with Pandas?
You can use pd.to_datetime from the pandas library. Here are various options, depending on what you want returned.
import pandas as pd
pd.to_datetime('today') # pd.to_datetime('now')
# Timestamp('2019-03-27 00:00:10.958567')
As a python datetime object,
pd.to_datetime('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 50, 42, 587629)
As a formatted date string,
pd.to_datetime('today').isoformat()
# '2019-04-18T04:03:32.493337'
# Or, `strftime` for custom formats.
pd.to_datetime('today').strftime('%Y-%m-%d')
# '2019-03-27'
To get just the date from the timestamp, call Timestamp.date.
pd.to_datetime('today').date()
# datetime.date(2019, 3, 27)
Aside from to_datetime, you can directly instantiate a Timestamp object using,
pd.Timestamp('today') # pd.Timestamp('now')
# Timestamp('2019-04-18 03:43:33.233093')
pd.Timestamp('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 53, 46, 220068)
If you want to make your Timestamp timezone aware, pass a timezone to the tz argument.
pd.Timestamp('now', tz='America/Los_Angeles')
# Timestamp('2019-04-18 03:59:02.647819-0700', tz='America/Los_Angeles')
Yet another date parser library: Pendulum
This one's good, I promise.
If you're working with pendulum, there are some interesting choices. You can get the current timestamp using now() or today's date using today().
import pendulum
pendulum.now()
# DateTime(2019, 3, 27, 0, 2, 41, 452264, tzinfo=Timezone('America/Los_Angeles'))
pendulum.today()
# DateTime(2019, 3, 27, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))
Additionally, you can also get tomorrow() or yesterday()'s date directly without having to do any additional timedelta arithmetic.
pendulum.yesterday()
# DateTime(2019, 3, 26, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))
pendulum.tomorrow()
# DateTime(2019, 3, 28, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))
There are various formatting options available.
pendulum.now().to_date_string()
# '2019-03-27'
pendulum.now().to_formatted_date_string()
# 'Mar 27, 2019'
pendulum.now().to_day_datetime_string()
# 'Wed, Mar 27, 2019 12:04 AM'
Rationale for this answer
A lot of pandas users stumble upon this question because they believe it is a python question more than a pandas one. This answer aims to be useful to folks who are already using these libraries and would be interested to know that there are ways to achieve these results within the scope of the library itself.
If you are not working with pandas or pendulum already, I definitely do not recommend installing them just for the sake of running this code! These libraries are heavy and come with a lot of plumbing under the hood. It is not worth the trouble when you can use the standard library instead.
from datetime import datetime
date = datetime.today().date()
print(date)
Use f-strings, they are usually the best choice for any text-variable mix:
from datetime import date
print(f'{date.today():%Y-%m-%d}')
Taken from Python f-string formatting not working with strftime inline which has the official links as well.
If you need e.g. pacific standard time (PST) you can do
from datetime import datetime
import pytz
tz = pytz.timezone('US/Pacific')
datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')
# '2021-09-02 10:21:41'
my code is a little complicated but I use it a lot
strftime("%y_%m_%d", localtime(time.time()))
reference:'https://strftime.org/
you can look at the reference to make anything you want
for you what YYYY-MM-DD just change my code to:
strftime("%Y-%m-%d", localtime(time.time()))
This works:
from datetime import date
today =date.today()
Output in this time: 2020-08-29
Additional:
this_year = date.today().year
this_month = date.today().month
this_day = date.today().day
print(today)
print(this_year)
print(this_month)
print(this_day)
To get day number from date is in python
for example:19-12-2020(dd-mm-yyy)order_date
we need 19 as output
order['day'] = order['Order_Date'].apply(lambda x: x.day)
I am using the datetime Python module in django. I am looking to calculate the date if the expiry date is less than or equal to 6 months from the current date.
The reason I want to generate a date 6 months from the current date is to set an alert that will highlight the field/column in which that event occurs. I dont know if my question is clear. I have been reading about timedelta function but cant really get my head round it. I am trying to write an if statement to statisfy this condition. Anyone able to help me please? Am a newbie to django and python.
There are two approaches, one only slightly inaccurate, one inaccurate in a different way:
Add a datetime.timedelta() of 365.25 / 2 days (average year length divided by two):
import datetime
sixmonths = datetime.datetime.now() + datetime.timedelta(days=365.25/2)
This method will give you a datetime stamp 6 months into the future, where we define 6 monhs as exactly half a year (on average).
Use the external dateutil library, it has a excellent relativedelta class that will add 6 months based on calendar calculations to your current date:
import datetime
from dateutil.relativedelat import relativedelta
sixmonths = datetime.datetime.now() + relativedelta(months=6)
This method will give you a datetime stamp 6 months into the future, where the month component of the date has been forwarded by 6, and it'll take into account month boundaries, making sure not to cross them. August 30th plus 6 months becomes February 28th or 29th (leap years permitting), for example.
A demonstration could be helpful. In my timezone, at the time of posting, this translates to:
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 2, 18, 12, 16, 0, 547567)
>>> now + datetime.timedelta(days=365.25/2)
datetime.datetime(2013, 8, 20, 3, 16, 0, 547567)
>>> now + relativedelta(months=6)
datetime.datetime(2013, 8, 18, 12, 16, 0, 547567)
So there is a 1 day and 15 hour difference between the two methods.
The same methods work fine with datetime.date objects too:
>>> today = datetime.date.today()
>>> today
datetime.date(2013, 2, 18)
>>> today + datetime.timedelta(days=365.25/2)
datetime.date(2013, 8, 19)
>>> today + relativedelta(months=6)
datetime.date(2013, 8, 18)
The half-year timedelta becomes a teensy less accurate when applied to dates only (the 5/8th day component of the delta is ignored now).
If by "6 months" you mean 180 days, you can use:
import datetime
d = datetime.date.today()
d + datetime.timedelta(6 * 30)
Alternatively if you, mean actual 6 months by calendar you'll have to lookup the calendar module and do some lookups on each month. For example:
import datetime
import calendar
def add_6_months(a_date):
month = a_date.month - 1 + 6
year = a_date.year + month / 12
month = month % 12 + 1
day = min(a_date.day,calendar.monthrange(year, month)[1])
return datetime.date(year, month, day)
I would give Delorean a look a serious look. It is built on top of dateutil and pytz to do what you asked would simply be the following.
>>> d = Delorean()
>>> d
Delorean(datetime=2013-02-21 06:00:21.195025+00:00, timezone=UTC)
>>> d.next_month(6)
Delorean(datetime=2013-08-21 06:00:21.195025+00:00, timezone=UTC)
It takes into account all the dateutil calculations as well as provide and interface for timezone shifts. to get the needed datetime simple .datetime on the Delorean object.
this might work for you in case you want to get an specfic date back:
from calendar import datetime
datetime.date(2019,1,1).strftime("%a %d")
#The arguments here are: year, month, day and the method is there to return a formated kind of date - in this case - day of the week and day of the month.
The outcome would be:
Tue 01
Hope it helps!