Python datetime formatting conversion - python

If I have a datetime object, like -
2012-03-10
How would I convert it into the following string format -
Sat, 10 Mar 2012 00:00:00 EDT

datetime.strptime("2012-03-10", "%Y-%m-%d").strftime("%a, %d %b %Y %H:%M:%S EDT")
Sorry about the primitive way of adding the timezone. See this question for better approaches.

>>> from datetime import datetime as dt
>>> a = dt.now().replace(tzinfo = pytz.timezone('US/Eastern'))
>>> a.strftime('%a, %d %b %Y %H:%M:%S %Z')
'Fri, 09 Mar 2012 20:02:51 EST'

Python 3.7+, using dateutil:
from datetime import datetime
from dateutil import tz
s = '2012-03-10'
dt = datetime.fromisoformat(s).replace(tzinfo=tz.gettz('US/Eastern'))
print(dt.strftime('%a, %d %b %Y %H:%M:%S %Z'))
>>> 'Sat, 10 Mar 2012 00:00:00 EST'
Python 3.9+, using zoneinfo:
from datetime import datetime
from zoneinfo import ZoneInfo
s = '2012-03-10'
dt = datetime.fromisoformat(s).replace(tzinfo=ZoneInfo('US/Eastern'))

Related

How to convert timezone in number to UTC?

I have some random dates with different timezones, they are in formats like this "07 Mar 2022 13:52:00 -0300", or they could be like this: "07 Mar 2022 11:12:00 -0700". I don't know which timezone exactly they will be coming from. How can I convert all of them to UTC time "0000Z"?
You can use standard module datetime for this.
Function strptime() (string parsing time) can convert string to object datetime using matching pattern. For your examples works pattern '%d %b %Y %H:%M:%S %z'
Next you can use .astimezone(datetime.timezone.utc) to convert to UTC.
And later you can format string with strftime() (string formatting time) using again pattern '%d %b %Y %H:%M:%S %z' (or you can skip %z)
Minimal working code:
import datetime
data = [
"07 Mar 2022 13:52:00 -0300",
"07 Mar 2022 11:12:00 -0700",
]
for item in data:
print('before str:', item)
dt = datetime.datetime.strptime(item, '%d %b %Y %H:%M:%S %z')
print('before dt :', dt)
dt = dt.astimezone(datetime.timezone.utc)
print('after dt :', dt)
print('after str:', dt.strftime('%d %b %Y %H:%M:%S %z'))
print('---')
Result:
before str: 07 Mar 2022 13:52:00 -0300
before dt : 2022-03-07 13:52:00-03:00
after dt : 2022-03-07 16:52:00+00:00
after str: 07 Mar 2022 16:52:00 +0000
---
before str: 07 Mar 2022 11:12:00 -0700
before dt : 2022-03-07 11:12:00-07:00
after dt : 2022-03-07 18:12:00+00:00
after str: 07 Mar 2022 18:12:00 +0000
---
I would suggest to import datetime, then use the following method to convert your time stamps into datetime objects (where str is the time stamp as a string): time_stamp = datetime.strptime(str, "%d %b %Y") (where the parameter after str gives information on the formatting; for details see here: https://www.programiz.com/python-programming/datetime/strptime).
After that, you can use datetime.astimezone() to convert this into another time zone.

Python datetime strptime() does not match format

I get the following error in which you can see the time data and the format I am using
time data '20:07:35 EEDT Wed Mar 31 2021' does not match format '%H:%M:%S %Z %a %b %d %Y'
I used the directives from here and I see that the format matches the description of each directive.
Can you see what is the issue here?
import datetime
time = '20:07:35 EEDT Wed Mar 31 2021'
time = time.replace('EEDT', '+0300')
datetime.datetime.strptime(time, '%H:%M:%S %z %a %b %d %Y')
you can map the abbreviated time zone to a IANA time zone name by dateutil's parser:
import dateutil
s = '20:07:35 EEDT Wed Mar 31 2021'
tzmapping = {"EEDT": dateutil.tz.gettz('Europe/Athens'),
"EEST": dateutil.tz.gettz('Europe/Athens')} # add more if needed...
dtobj = dateutil.parser.parse(s, tzinfos=tzmapping)
that will give you
dtobj
# >>> datetime.datetime(2021, 3, 31, 20, 7, 35, tzinfo=tzfile('Europe/Athens'))
dtobj.utcoffset()
# >>> datetime.timedelta(seconds=10800) # UTC+3
Note that timedelta arithmetic works correctly, i.e. includes DST changes:
from datetime import timedelta
dtobj -= timedelta(7) # DST change: dtobj is now EEST, UTC+2
dtobj.utcoffset()
# >>> datetime.timedelta(seconds=7200)
Problem is with EEDT. If you ignore EEDT(quickfix, not ideal), then your code may look like:
text = '20:07:35 EEDT Wed Mar 31 2021';
fmt = '%H:%M:%S EEDT %a %b %d %Y';
datetime.strptime(text, fmt)
--edit--
parsing datetime with timezone is difficult to pure datetime module. I'm not big expert, but pytz or python-datetutil should be good choice, according to this page: https://medium.com/#nqbao/python-timezone-and-daylight-savings-e511a0093d0
For those who are interested in different approach for similar, like GMT and BST or EEST and EEDT, it can be represented like this:
import datetime
try:
Time1 = datetime.datetime.strptime(DropTm,"%a %b %d %H:%M:%S GMT %Y")
except:
Time1 = datetime.datetime.strptime(DropTm,"%a %b %d %H:%M:%S BST %Y")
In your situation it will be:
import datetime
try:
Time1 = datetime.datetime.strptime(SomeValue,"%H:%M:%S EEDT %a %b %d %Y")
except:
Time1 = datetime.datetime.strptime(SomeValue,"%H:%M:%S EEST %a %b %d %Y")
Where is "SomeValue" your data!!
It did worked for me and do not need any other libraries! Good Luck with coding!!!

How to fix ValueError time date does not match format when converting from string to datetime

Im trying to convert a string to datetime and keep getting the error: ValueError: time data 'Mon, 22 Apr 2019 17:04:38 +0200 (CEST)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'
from datetime import datetime
s = "Mon, 22 Apr 2019 17:04:38 +0200 (CEST)"
d = datetime.strptime(s, '%a, %d %b %Y %H:%M:%S %z %Z')
What am i missing?
%Z is generally used for converting into string format. In any case, it is the offset, not the name of the time zone.
The rest of your code is valid, however:
s = "Mon, 22 Apr 2019 17:04:38 +0200"
d = datetime.strptime(s, '%a, %d %b %Y %H:%M:%S %z')
datetime only comes with the ability to parse UTC and whatever local time zone is listed in time.tzname. It can't match (CEST) because it doesn't know what timezone that is (It would also be redundant because you defined the timezone using the offset +0200).
You will need to implement your own (CEST) using datetime.tzinfo or by importing an external library like pytz or pendulum in order to parse (CEST) from a string into a datetime.timezone.
Also, don't forget to include parenthesis() in your match string.
This code passes, however, I do not know what happens to 'CEST' once it is converted into the string.
from datetime import datetime
tz = 'CEST'
s = "Mon, 22 Apr 2019 17:04:38 +0200 " + tz
d = datetime.strptime(s, '%a, %d %b %Y %H:%M:%S %z ' + tz)

How to convert time in this format to local time zone?

I'd like to convert this time Sat, 19 May 2018 16:32:56 +0000 to 20180519-113256 in a local timezone (EDT in this example) in python. Could anybody show me how to do it?
PS., The following example shows how to convert time to local timezone. But I am not sure how to parse Sat, 19 May 2018 16:32:56 +0000.
Convert UTC datetime string to local datetime with Python
You could choose any timezone you want:
import pytz
from datetime import datetime
s = 'Sat, 19 May 2018 16:32:56 +0000'
dt = datetime.strptime(s, '%a, %d %b %Y %H:%M:%S %z')
tz = pytz.timezone('America/Chicago')
new_s = dt.astimezone(tz).strftime('%Y%m%d-%H%M%S')
for me this works:
from datetime import datetime
from dateutil import tz
def convert(date, from_zone = 'UTC', to_zone='America/New_York'):
from_zone = tz.gettz(from_zone)
to_zone = tz.gettz(to_zone)
date = date.replace(tzinfo=from_zone)
central = date.astimezone(to_zone)
return date
s = "Sat, 19 May 2018 16:32:56 +0000"
d = datetime.strptime(s, '%a, %d %B %Y %H:%M:%S +%f')
d = convert(d)

Calculating days using string dates in Python

I have dates in the current string format: 'Tue Feb 19 00:09:28 +1100 2013'
I'm trying to figure out how many days have passed between the date in the string and the present date.
I've been able to convert the string into a date.
import time
day = time.strptime('Tue Feb 19 00:09:28 +1100 2013', '%a %b %d %H:%M:%S +1100 %Y')
Use the datetime module instead:
import datetime
day = datetime.datetime.strptime('Tue Feb 19 00:09:28 +1100 2013', '%a %b %d %H:%M:%S +1100 %Y')
delta = day - datetime.datetime.now()
print delta.days
Subtracting two datetime.datetime values returns a datetime.timedelta object, which has a days attribute.
Your strings do contain a timezone offset, and you hardcoded it to match; if the value varies you'll have to use a parser that can handle the offset. The python-dateutil package includes both an excellent parser and the timezone support to handle this:
>>> from dateutil import parser
>>> parser.parse('Tue Feb 19 00:09:28 +1100 2013')
datetime.datetime(2013, 2, 19, 0, 9, 28, tzinfo=tzoffset(None, 39600))
Note that because this result includes the timezone, you now need to use timezone-aware datetime objects when using date arithmetic:
>>> from dateutil import tz
>>> import datetime
>>> utcnow = datetime.datetime.now(tz.tzutc())
>>> then = parser.parse('Tue Feb 19 00:09:28 +1100 2013')
>>> utcnow - then
datetime.timedelta(31, 12087, 617740)
>>> (utcnow - then).days
31
I created a utcnow variable in the above example based of the UTC timezone before calculating how long ago the parsed date was.

Categories