Custom date format parsing in python - python

I am trying to the parse dates of the format '2016-04-15T12:24:20.707Z' in Python, tried strptime, doesn't work and I also tried django parse_datetime but it only returns none as the value

You may try this way :
from datetime import datetime
date_str = '2016-04-15T12:24:20.707Z'
date = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ")
print(date)
Output:
2016-04-15 12:24:20.707000

You have to specify the format as "%Y-%m-%dT%H:%M:%S.%fZ" while conversion
In [11]: from datetime import datetime
In [12]: out_format = "%Y-%m-%d"
In [13]: input_format="%Y-%m-%dT%H:%M:%S.%fZ"
In [14]: date_time_obj = datetime.strptime(time,input_format)
In [15]: date_time_obj
Out[15]: datetime.datetime(2016, 4, 15, 12, 24, 20, 707000)
In [16]: date_time_str = date_time_obj.strftime(out_format)
In [17]: date_time_str
Out[17]: '2016-04-15'

import dateutil.parser
from datetime import datetime
dt = dateutil.parser.parse('2016-04-15T12:24:20.707Z')

This seems to be working alright:
import dateparser
dateparser.parse('2016-04-15T12:24:20.707Z')
> datetime.datetime(2016, 4, 15, 12, 24, 20, 707000, tzinfo=<StaticTzInfo 'Z'>)

Probably iso8601 package is what you need

You may try this way if you need something on the fly:
This returns the current datetime in UTC, as a datetime object then immediately converts it to your preferred custom format.
from datetime import datetime, timezone
from time import strftime
# Get UTC Time datetime object and convert it to your preferred format.
print(f"Regular : { datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S') }") # Regular : 2022-06-04 23:08:27
print(f"Log Format: { datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S') }") # Log Format: 20220604_230827
print(f"YMD Format: { datetime.now(timezone.utc).strftime('%Y-%m-%d') }") # YMD Format: 2022-06-04
print(f"Time Format: { datetime.now(timezone.utc).strftime('%H:%M:%S') }") # Time Format: 23:08:27
# Without the f'String'
print(datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')) # Regular : 2022-06-04 23:08:27
print(datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')) # Log Format: 20220604_230827
print(datetime.now(timezone.utc).strftime('%Y-%m-%d')) # YMD Format: 2022-06-04
print(datetime.now(timezone.utc).strftime('%H%M%S')) # Time Format: 23:08:27
# Details:
# Get current DateTime in UTC
datetime.now(timezone.utc)
# datetime.datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=datetime.timezone.utc)
type(datetime.now(timezone.utc))
# <class 'datetime.datetime'>
# Use the strftime on the datetime object directly
datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
# '2022-06-04 23:13:27'
type(datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S'))
# <class 'str'>

Related

Convert Date time to human readable formate python

I have a date time string something like this
2022-03-21 16:29:01.8593
but I want it to be like
03/21/2022 02:16 PM
Use datetime module:
from datetime import datetime
d = datetime.strptime('2022-03-21 16:29:01.8593', '%Y-%m-%d %H:%M:%S.%f')
s = d.strftime('%m/%d/%Y %I:%M %p')
Output:
>>> d
datetime.datetime(2022, 3, 21, 16, 29, 1, 859300)
>>> s
'03/21/2022 04:29 PM'
Use this link as documentation.

Python time zone conversion from UTC to EST

I have the below list in python.
[['File_1','2021-09-09 07:05:10'],['File_2','2021-09-08 08:05:11']]
The above timestamp is a string in UTC timezone. I would like to convert this to EST timezone.
I tried using pytz package using
datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S').astimezone(pytz.timezone('US/Eastern'))
but it gives me result like
['File_1',datetime.datetime(2021,09,03,4,20,5)].
The format of date time is not as expected.
you need to set UTC first, then convert to the desired tz:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo # Python 3.9+ standard lib
l = [['File_1','2021-09-09 07:05:10'],['File_2','2021-09-08 08:05:11']]
out = [[i[0], datetime.fromisoformat(i[1]) # Python 3.7+
.replace(tzinfo=timezone.utc)
.astimezone(ZoneInfo("America/New_York"))] for i in l]
print(out)
# [['File_1', datetime.datetime(2021, 9, 9, 3, 5, 10, tzinfo=zoneinfo.ZoneInfo(key='America/New_York'))], ['File_2', datetime.datetime(2021, 9, 8, 4, 5, 11, tzinfo=zoneinfo.ZoneInfo(key='America/New_York'))]]
# with pytz:
import pytz
outp = [[i[0], datetime.fromisoformat(i[1]) # Python 3.7+
.replace(tzinfo=timezone.utc)
.astimezone(pytz.timezone("America/New_York"))] for i in l]
print(outp)
# [['File_1', datetime.datetime(2021, 9, 9, 3, 5, 10, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)], ['File_2', datetime.datetime(2021, 9, 8, 4, 5, 11, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)]]
If you want a string instead of datetime object, use strftime or even simpler: .isoformat().
You can use the below snippet to get your output in the same format as your input
from datetime import datetime
import pytz
from pytz import timezone
timestamp = '2021-09-09 07:05:10'
datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S').astimezone(pytz.timezone('US/Eastern')).strftime("%Y-%m-%d %H:%M:%S")
# Output
'2021-09-09 03:05:10'
If you wish to display the timezone in the format, you can use
datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S').astimezone(pytz.timezone('US/Eastern')).strftime("%Y-%m-%d %H:%M:%S %Z%z")
# Output
'2021-09-09 03:05:10 EDT-0400'
Here's one way to convert it to EST
1st. Declare the list, and identify the date you want to convert as string
list = [['File_1','2021-09-09 07:05:10'],['File_2','2021-09-08 08:05:11']]
date_to_convert = list[1][1]
2nd. Import the needed libraries
import pytz
from datetime import datetime,timezone
3rd. Convert the string to date time
d = datetime.fromisoformat(date_to_convert)
4th. Declare datetime timezone as utc.
d = date_to_string.replace(tzinfo=timezone.utc)
print(d.isoformat())
# the output for the above: '2021-09-08T08:05:11+00:00'
5th. Set the format and convert to EST
fmt = '%Y-%m-%d %H:%M:%S'
est_date = d.astimezone(pytz.timezone('US/Eastern')).strftime(fmt)
print(est_date)
# the output for the above: '2021-09-08 04:05:11'
USE THIS WAY REMBER UPERCASE AND LOWERCASE ALSO MATTER
import time
timer = time.strftime("%Y-%m-%d -- %H:%M:%S %p")
print(timer)

Convert string to datetime python with milli-seconds

Problem: I have the following string '2021-03-10T09:58:17.027323+00:00' which I want to convert to datetime. I have difficulties with the format. This is what I tried so far:
datetime.strptime('2021-03-10T09:58:17.027323+00:00', "%Y-%m-%dT%H:%M:%S.z")
Any help is highly appreciated!
The correct format string is "%Y-%m-%dT%H:%M:%S.%f%z"
>>> from datetime import datetime
>>> datetime.strptime('2021-03-10T09:58:17.027323+00:00', "%Y-%m-%dT%H:%M:%S.%f%z")
datetime.datetime(2021, 3, 10, 9, 58, 17, 27323, tzinfo=datetime.timezone.utc)
>>> datetime.fromisoformat('2021-03-10T09:58:17.027323+00:00')
datetime.datetime(2021, 3, 10, 9, 58, 17, 27323, tzinfo=datetime.timezone.utc)
But as mentioned in the comments - better use fromisoformat()
Given that your string is known from before and you won't be using a now time feature, you can check here I think you can use the following code:
import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)

Get file modification date in MM-DD-YYYY format without time [duplicate]

I have a date string and want to convert it to the date type:
I have tried to use datetime.datetime.strptime with the format that I want but it is returning the time with the conversion.
when = alldates[int(daypos[0])]
print when, type(when)
then = datetime.datetime.strptime(when, '%Y-%m-%d')
print then, type(then)
This is what the output returns:
2013-05-07 <type 'str'>
2013-05-07 00:00:00 <type 'datetime.datetime'>
I need to remove the time: 00:00:00.
print then.date()
What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now remains unchanged.
>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
To convert a string into a date, the easiest way AFAIK is the dateutil module:
import dateutil.parser
datetime_object = dateutil.parser.parse("2013-05-07")
It can also handle time zones:
print(dateutil.parser.parse("2013-05-07"))
>>> datetime.datetime(2013, 5, 7, 1, 12, 12, tzinfo=tzutc())
If you have a datetime object, say:
import pytz
import datetime
now = datetime.datetime.now(pytz.UTC)
and you want chop off the time part, then I think it is easier to construct a new object instead of "substracting the time part". It is shorter and more bullet proof:
date_part datetime.datetime(now.year, now.month, now.day, tzinfo=now.tzinfo)
It also keeps the time zone information, it is easier to read and understand than a timedelta substraction, and you also have the option to give a different time zone in the same step (which makes sense, since you will have zero time part anyway).
For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:
date = datetime.datetime.utcnow()
start_of_day = date - datetime.timedelta(
hours=date.hour,
minutes=date.minute,
seconds=date.second,
microseconds=date.microsecond
)
end_of_day = start_of_day + datetime.timedelta(
hours=23,
minutes=59,
seconds=59
)
Example output:
>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)
If you specifically want a datetime and not a date but want the time zero'd out you could combine date with datetime.min.time()
Example:
datetime.datetime.combine(datetime.datetime.today().date(),
datetime.datetime.min.time())
You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].
You can pass this as map/apply to use it in a dataframe/series too.
You can usee the following code:
week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]

How to convert JSON date & time to Python datetime?

I get the date and time as string like 2014-05-18T12:19:24+04:00
I found another question explaining how to handle dates in UTC timezone (2012-05-29T19:30:03.283Z)
What should I do with +04:00 in my case (if I want to store time in UTC timezone in Python)?
Upd. I've tried to parse it like below:
dt = '2014-05-19T14:48:50+04:00'
plus_position = dt.find('+') # remove column in the timezone part
colon_pos = dt.find(':', plus_position)
dt = dt[:colon_pos] + dt[colon_pos+1:]
dt = datetime.datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S%z') # '2014-05-19T14:48:50+0400'
But it fails - 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'
Using dateutil:
>>> import dateutil.parser
>>> dateutil.parser.parse('2014-05-18T12:19:24+04:00')
datetime.datetime(2014, 5, 18, 12, 19, 24, tzinfo=tzoffset(None, 14400))

Categories

Resources