Check validity of datetime? - python

I would like to create a setter method for a datetime object so that I can customize the replace method. Is this possible?
For example:
datetime = datetime.replace(day = 34)
This throws an error because 34 is not a valid number of days for any month, but what I would like to do is increase the month by 1 and then subtract 28, 30, or 31 days.

You can subclass datetime and provide your own implementation of the replace method.

this doesn't answer your question directly, but if you're just trying to increment the datetime object, you can use timedelta. For example:
from datetime import datetime
from datetime import timedelta
datetime(2011, 1, 1) + timedelta(days=34)

Related

Subtract "n" days from a list of format [month, day]

I have a this list in the Python.
dates= [6,15],[8,24]
I want to subtract values from this list. For example [6,15] is [month,day] so I want to subtract 15 to 10. I want to get [6,5], well this operation will repeat after that I want to get [5, 26] like this. How can I do this code?
You probably want to use the builtin datetime and 3rd-party dateutil modules for this. Note you will need to specify a year, since some years have months of differing lengths (i.e leap years) -parse will assume the current year:
import datetime.date as dt
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
print(parse('6/15') - relativedelta(days=10))
You should be using inbuilt datetime.datetime and datetime.timedelta objects to achieve this in simplified way as:
>>> from datetime import datetime, timedelta
>>> my_date_list = [6, 15] # your current list in "[month, day]" format
# create `datetime` object using above values
# since you don't care about year, using 2018 for demonstration. But you need this.
>>> datetime_obj = datetime(month=my_date_list[0], day=my_date_list[1], year=2018)
# timedelta object for the number of days you want the diff
>>> diff = timedelta(days=20)
# New datetime object
>>> new_datetime_obj = datetime_obj - diff
>>> new_datetime_obj
datetime.datetime(2018, 5, 26, 0, 0)
# You desired format list of [month, day]
>>> [new_datetime_obj.month, new_datetime_obj.day]
[5, 26]
PS: You shouldn't be even storing your initial and final list as "[Month, Day]" format. Simply store the list of datetime objects, and use it where ever you need. new_datetime_obj.month yields the month and new_datetime_obj.day yields the day
Note: You must consider about the year in your code. It is necessary in doing your computation and calculating the days. For example, the calculation for February for leap year and non-leap years yields different results.

Getting today's date in YYYY-MM-DD in Python?

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)

How can I convert data into "ddmmyyyy hh:mm:ss"?

All that I have is the number 223 (which is the number of days from Jan 01,2012), and the time at which the event occurred at (for example: 09, 55, 56.38 = (hh, mm, ss)).
In Excel I can get a serial number - in the format 10-Aug-12 09:55:56 - with these four numbers.
In Python I've been having some troubles doing the same. Does anyone have any idea about what commands I could be using?
The timedelta class in Python's datetime module lets you create a time difference, in days (or other units), which you can add to/subtract from datetime objects to get a new date.
(Note: the datetime module contains a datetime object. Yup.)
So, you could construct a datetime object using 1st Jan 2012 and the hour, minute and second values you've got, and then add a timedelta of 223 days to it.
To get that datetime as a string in your desired format, the strftime method on the datetime object is your friend.
Putting it all on one line:
from datetime import datetime, timedelta
serial_number = (datetime(2012, 1, 1, 9, 55, 56) + timedelta(223)).strftime('%d-%h-%y %H:%M:%S')

Problems constructing a datetime obj?

I'm trying to make a object with the same year and month as the current date but change the day around to a different date in the month.
from datetime import timedelta, date, datetime
whole = date.today()
wholestr= str(whole)
vali = wholestr.split('-')
year=int(vali[0])
month=int(vali[1])
day=int(vali[2])
sub = datetime.date(year,month,16)
print sub
Here it says that ints work when constructing but I get an error saying that it needs a datetime.date obj and not ints.
http://docs.python.org/library/datetime.html#date-objects
I believe your problem is that you call datetime.date when you just want to call date in your second to last line. Changing to just using date gave me this result:
>>> from datetime import timedelta, date, datetime
>>> whole = date.today()
>>> wholestr = str(whole)
>>> vali = wholestr.split('-')
>>> year = int(vali[0])
>>> month = int(vali[1])
>>> day = int(vali[2])
>>> sub = date(year, month, 16)
>>> sub
datetime.date(2012, 4, 16)
>>> print sub
2012-04-16
Alternatively you could just call datetime like this:
>>> datetime(year, month, 16)
datetime.datetime(2012, 4, 16, 0, 0)
Personally, this is why I always prefer to just do import datetime.
Your problem is pretty straightforward:
from datetime import [some items including] datetime
After the import finishes, datetime refers to what used to be called datetime.datetime, and datetime.date is what would otherwise be referred to as datetime.datetime.date.
You can either use date (which, since you imported it, now refers to what would otherwise be datetime.date) or just import datetime and qualify all the names, e.g., whole = datetime.date.today() and so on. I prefer the latter myself because it's easy to get lost otherwise, but it's a personal preference thing.

can't compare datetime.datetime to datetime.date

I have the following code and am getting the above error. Since I'm new to python I'm having trouble understanding the syntax here and how I can fix the error:
if not start or date < start: start = date
There is a datetime.date() method for converting from a datetime to a date.
To do the opposite conversion, you could use this function datetime.datetime(d.year, d.month, d.day)
You can use the datetime.datetime.combine method to compare the date object to datetime object, then compare the converted object with the other datetime object.
import datetime
dt1 = datetime.datetime(2011, 03, 03, 11, 12)
day = datetime.date(2011, 03, 02)
dt2 = datetime.datetime.combine(day, datetime.time(0, 0))
print dt1 > dt2
Assuming start is a datetime, Use it like this:
if not start or date < start.date(): start = date
I don't think there is a need to convert date to datetime in python, as you can just do the opposite and compare.
Or else you have other methods to create a new datetime by using the date to convert and time at 00:00.
Wow, question and answers are too old, it needs update. Converting datetime.datetime object to datetime.date object is just easy:
somestringtext = '7.04.2021'
datetime_datetime_object = datetime.strptime(somestringtext, '%d.%m.%Y')
### returns datetime.datetime(2021, 4, 7, 0, 0)
datetime_date_object = datetime.date(datetime_datetime_object)
And datetime object is not same as date object, you cant compare
datetime_datetime_object == datetime_date_object
### returns False
unless you convert them to same format:
datetime.date(datetime_datetime_object) == datetime_date_object
### returns True
I was receiving the above error while using pandas, however, because the date_column was the string I wasted a lot of time without realizing I was formatting the wrong thing:
# didnt work
df[(df.date_column > parse_datestr('2018-01-01'))]
# works
df['date_column'] = pd.to_datetime(df['date_column'])
df[(df.date_column > '2018-01-01') & (df.date_column < '2018-02-28')]
This problem arises when you are trying to compare a date field (DateField) and a datetime field (DateTimeField).
The solution would be check where you defined the fields in your models and ensure that the types are uniform.
I would suggest you replace all DateField with DateTimeField.
Your variables start and date are of different type I guess. One is a datetime and one is a date. You may have to show more code in order to get decent help.
But look at this: http://docs.python.org/library/datetime.html#available-types
It tells you that datetime.datetime has attributes like day, month and year, just like datetime.date.
I solved it using .date() function available with datetime object. Here is how:
date_object = datetime_object.date()
and then you can compare it with any datetime.date object. Hope this helps.

Categories

Resources