Easier way to create date object from string - python

I'm working on an image upload utility, and part of the functionality is to parse the IPTC and EXIF data of the images.
IPTCInfo gets the information I need, but the date fields are in the format 20130925.
Now, I can break that integer up into 2013 09 25 and create a date object. Before I do so, is there already existing functionality to solve this issue?

The date class doesn't have a string-parsing function, but the datetime class does, strptime.
So, first make a datetime, then extract the date part of it:
>>> s = '20130925'
>>> dt = datetime.datetime.strptime(s, '%Y%m%d')
>>> d = dt.date()
>>> d
datetime.date(2013, 9, 25)
If you don't understand where the '%Y%m%d' comes from, see strftime() and strptime() Behavior.

You can use datetime.strptime:
>>> import datetime
>>> datetime.datetime.strptime("20130925","%Y%m%d").date()
datetime.date(2013, 9, 25)

Related

Convert date to ordinal python?

I want to convert
2010-03-01 to 733832
I just found this toordinal code
d=datetime.date(year=2010, month=3, day=1)
d.toordinal()
from this
But i want something more like
d=datetime.date('2010-03-01')
d.toordinal()
Thanks in advance
You'll need to use strptime on the date string, specifying the format, then you can call the toordinal method of the date object:
>>> from datetime import datetime as dt
>>> d = dt.strptime('2010-03-01', '%Y-%m-%d').date()
>>> d
datetime.date(2010, 3, 1)
>>> d.toordinal()
733832
The call to the date method in this case is redundant, and is only kept for making the object consistent as a date object instead of a datetime object.
If you're looking to handle more date string formats, Python's strftime directives is one good reference you want to check out.
like this:
datetime.strptime("2016-01-01", "%Y-%m-%d").toordinal()
You need to firstly convert the time string to datetime object using strptime(). Then call .toordinal() on the datetime object
>>> from datetime import datetime
>>> date = datetime.strptime('2010-03-01', '%Y-%M-%d')
>>> date.toordinal()
733773
It is even better to create a function to achieve this as:
def convert_date_to_ordinal(date):
return datetime.strptime(date, '%Y-%M-%d').toordinal()
convert_date_to_ordinal('2010-03-01')
#returns: 733773

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)

Date Time Formats in Python

What are these date-time formats? I need to convert them to the same format, to check if they are the same. These are just two coming from a separate data source, so I need to find a way to make them the same format. Any ideas?
2013-07-12T07:00:00Z
2013-07-10T11:00:00.000Z
Thanks in advance
That extra .000 is micro seconds.
This will convert a date string of a format to datetime object.
import datetime
d1 = datetime.datetime.strptime("2013-07-12T07:00:00Z","%Y-%m-%dT%H:%M:%SZ")
d2 = datetime.datetime.strptime("2013-07-10T11:00:00.000Z","%Y-%m-%dT%H:%M:%S.%fZ")
Then convert them into any format depending on your requirement, by using:
new_format = "%Y-%m-%d"
d1.strftime(new_format)
perhaps use .isoformat()
string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM]
>>> import datetime
>>> datetime.datetime.utcnow().isoformat() + "Z"
'2013-07-11T22:26:51.564000Z'
>>>
Z specifies "zulu" time or UTC.
You can also add the timezone component by making your datetime object timezone aware by applying the appropriate tzinfo object. With the tzinfo applied the .isoformat() method will include the appropriate utc offset in the output:
>>> d = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
>>> d.isoformat()
'2019-11-11T00:52:43.349356+00:00'
You can remove the microseconds by change the microseconds value to 0:
>>> no_ms = d.replace(microsecond=0)
>>> no_ms.isoformat()
'2019-11-11T00:52:43+00:00'
Also, as of python 3.7 the .fromisoformat() method is available to load an iso formatted datetime string into a python datetime object:
>>> datetime.datetime.fromisoformat('2019-11-11T00:52:43+00:00')
datetime.datetime(2019, 11, 11, 0, 52, 43, tzinfo=datetime.timezone.utc)
http://www.ietf.org/rfc/rfc3339.txt
you can try to trim the string
data = "2019-10-22T00:00:00.000-05:00"
result1 = datetime.datetime.strptime(data[0:19],"%Y-%m-%dT%H:%M:%S")
result2 = datetime.datetime.strptime(data[0:23],"%Y-%m-%dT%H:%M:%S.%f")
result3 = datetime.datetime.strptime(data[0:9], "%Y-%m-%d")
use datetime module.
For a variable
import datetime
def convertDate(d):
new_date = datetime.datetime.strptime(d,"%Y-%m-%dT%H:%M:%S.%fZ")
return new_date.date()
convertDate("2019-12-23T00:00:00.000Z")
you can change the ".date()" to ".year", ".month", ".day" etc...
Output: # is now a datetime object
datetime.date(2019, 12, 23)
For a DataFrame column, use apply()
df['new_column'] = df['date_column'].apply(convertDate)
* Short and best way:
str(datetime.datetime.now()).replace(' ','T')
or
str(datetime.datetime.now()).replace(' ','T') + "Z"

How to convert a timezone aware string to datetime in Python without dateutil?

I have to convert a timezone-aware string like "2012-11-01T04:16:13-04:00" to a Python datetime object.
I saw the dateutil module which has a parse function, but I don't really want to use it as it adds a dependency.
So how can I do it? I have tried something like the following, but with no luck.
datetime.datetime.strptime("2012-11-01T04:16:13-04:00", "%Y-%m-%dT%H:%M:%S%Z")
As of Python 3.7, datetime.datetime.fromisoformat() can handle your format:
>>> import datetime
>>> datetime.datetime.fromisoformat('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
In older Python versions you can't, not without a whole lot of painstaking manual timezone defining.
Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you.
As a side-effect, this means that timezone parsing also needs to be an external library. If dateutil is too heavy-weight for you, use iso8601 instead, it'll parse your specific format just fine:
>>> import iso8601
>>> iso8601.parse_date('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=<FixedOffset '-04:00'>)
iso8601 is a whopping 4KB small. Compare that tot python-dateutil's 148KB.
As of Python 3.2 Python can handle simple offset-based timezones, and %z will parse -hhmm and +hhmm timezone offsets in a timestamp. That means that for a ISO 8601 timestamp you'd have to remove the : in the timezone:
>>> from datetime import datetime
>>> iso_ts = '2012-11-01T04:16:13-04:00'
>>> datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))
The lack of proper ISO 8601 parsing is being tracked in Python issue 15873.
Here is the Python Doc for datetime object using dateutil package..
from dateutil.parser import parse
get_date_obj = parse("2012-11-01T04:16:13-04:00")
print get_date_obj
There are two issues with the code in the original question: there should not be a : in the timezone and the format string for "timezone as an offset" is lower case %z not upper %Z.
This works for me in Python v3.6
>>> from datetime import datetime
>>> t = datetime.strptime("2012-11-01T04:16:13-0400", "%Y-%m-%dT%H:%M:%S%z")
>>> print(t)
2012-11-01 04:16:13-04:00
You can convert like this.
date = datetime.datetime.strptime('2019-3-16T5-49-52-595Z','%Y-%m-%dT%H-%M-%S-%f%z')
date_time = date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
You can create a timezone unaware object and replace the tzinfo and make it a timezone aware DateTime object later.
from datetime import datetime
import pytz
unware_time = datetime.strptime("2012-11-01 04:16:13", "%Y-%m-%d %H:%M:%S")
aware_time = unaware_time.replace(tzinfo=pytz.UTC)
I'm new to Python, but found a way to convert
2017-05-27T07:20:18.000-04:00
to
2017-05-27T07:20:18 without downloading new utilities.
from datetime import datetime, timedelta
time_zone1 = int("2017-05-27T07:20:18.000-04:00"[-6:][:3])
>>returns -04
item_date = datetime.strptime("2017-05-27T07:20:18.000-04:00".replace(".000", "")[:-6], "%Y-%m-%dT%H:%M:%S") + timedelta(hours=-time_zone1)
I'm sure there are better ways to do this without slicing up the string so much, but this got the job done.
This suggestion for using dateutil by Mohideen bin Mohammed definitely is the best solution even if it does a require a small library. having used the other approaches there prone to various forms of failure. Here's a nice function for this.
from dateutil.parser import parse
def parse_date_convert(date, fmt=None):
if fmt is None:
fmt = '%Y-%m-%d %H:%M:%S' # Defaults to : 2022-08-31 07:47:30
get_date_obj = parse(str(date))
return str(get_date_obj.strftime(fmt))
dates = ['2022-08-31T07:47:30Z','2022-08-31T07:47:29.098Z','2017-05-27T07:20:18.000-04:00','2012-11-01T04:16:13-04:00']
for date in dates:
print(f'Before: {date} After: {parse_date_convert(date)}')
Results:
Before: 2022-08-31T07:47:30Z After: 2022-08-31 07:47:30
Before: 2022-08-31T07:47:29.098Z After: 2022-08-31 07:47:29
Before: 2017-05-27T07:20:18.000-04:00 After: 2017-05-27 07:20:18
Before: 2012-11-01T04:16:13-04:00 After: 2012-11-01 04:16:13
Having tried various forms such as slicing split replacing the T Z like this:
dates = ['2022-08-31T07:47:30Z','2022-08-31T07:47:29.098Z','2017-05-27T07:20:18.000-04:00','2012-11-01T04:16:13-04:00']
for date in dates:
print(f'Before: {date} After: {date.replace("T", " ").replace("Z", "")}')
You still are left with subpar results. like the below
Before: 2022-08-31T07:47:30Z After: 2022-08-31 07:47:30
Before: 2022-08-31T07:47:29.098Z After: 2022-08-31 07:47:29.098
Before: 2017-05-27T07:20:18.000-04:00 After: 2017-05-27 07:20:18.000-04:00
Before: 2012-11-01T04:16:13-04:00 After: 2012-11-01 04:16:13-04:00

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