Convert Date time to human readable formate python - 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.

Related

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)

how to convert sqlite3 datetime to 24 hrs

I am parsing through a JSON file with a string of datetime like this:
"col_datetime": "10/18/2017 2:45:00 PM"
I am using python's datetime.strptime to make this a sqlite datetime:
datetime.strptime(col_datetime, '%m/%d/%Y %H:%M:%S %p')
this is stored in the sqlite table like this:
2017-10-18 02:45:00.000000
But when I try to parse this using strftime in sqlite3 it seems not getting the PM
strftime('%H:%M',col_datetime)
This returns to:
2:45
Instead of:
14:45
Any thoughts on this?
You need to use %I for 12 hour format in strptime instead of %H.
Here's an example where you can see it works as expected with that change:
>>> datetime.strptime('10/18/2017 2:45:00 PM', '%m/%d/%Y %H:%M:%S %p')
datetime.datetime(2017, 10, 18, 2, 45)
>>> datetime.strptime('10/18/2017 2:45:00 PM', '%m/%d/%Y %I:%M:%S %p')
datetime.datetime(2017, 10, 18, 14, 45)

Custom date format parsing in 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'>

Getting the UTC hour from a UTC+2 datetime object

My Time string looks like this:
03/16/16 15:50 UTC+02:00
so I parse it like so
from dateutil import parser
my_date = parser.parse(date_string)
Since this is UTC+2 time, how do I convert this dateobject to UTC?
Using datetime.datetime.astimezone with pytz.UTC (datetime.timezone.utc if you use Python 3.x), you can get the datetime with UTC timezone:
>>> import pytz
>>> from dateutil import parser
>>>
>>> date_string = '03/16/16 15:50 UTC+02:00'
>>> my_date = parser.parse(date_string)
>>> my_date.astimezone(pytz.UTC)
datetime.datetime(2016, 3, 16, 17, 50, tzinfo=<UTC>)

Python Datetime : use strftime() with a timezone-aware date

Suppose I have date d like this :
>>> d
datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200))
As you can see, it is "timezone aware", there is an offset of 2 Hour, utctime is
>>> d.utctimetuple()
time.struct_time(tm_year=2009, tm_mon=4, tm_mday=19,
tm_hour=23, tm_min=12, tm_sec=0,
tm_wday=6, tm_yday=109, tm_isdst=0)
So, real UTC date is 19th March 2009 23:12:00, right ?
Now I need to format my date in string, I use
>>> d.strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-04-19 21:12:00.000000'
Which doesn't seems to take this offset into account. How to fix that ?
In addition to what #Slam has already answered:
If you want to output the UTC time without any offset, you can do
from datetime import timezone, datetime, timedelta
d = datetime(2009, 4, 19, 21, 12, tzinfo=timezone(timedelta(hours=-2)))
d.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')
See datetime.astimezone in the Python docs.
The reason is python actually formatting your datetime object, not some "UTC at this point of time"
To show timezone in formatting, use %z or %Z.
Look for strf docs for details
This will convert your local time to UTC and print it:
import datetime, pytz
from dateutil.tz.tz import tzoffset
loc = datetime.datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200))
print(loc.astimezone(pytz.utc).strftime('%Y-%m-%d %H:%M:%S.%f') )
(http://pytz.sourceforge.net/)
I couldn't import timezone module (and hadn't much time to know why)
so I set TZ environment variable which override the /etc/localtime information
>>> import os
>>> import datetime
>>> print datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
2019-05-17 11:26
>>> os.environ["TZ"] = "UTC"
>>> print datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
2019-05-17 09:26

Categories

Resources