I have a list of dates stored as strings. I need to convert them to this format "%Y%m%d %H:%M:%S %Z"
I can not achieve this since the date stored as a string has no time, just the date. eg. 2015-06-12
below is one iteration of the code/idea i tried but failed. any suggestions are greatly appreciated!
d = "2015-06-12"
x = datetime.datetime.strptime(d, "%Y-%m-%d").date()
x = datetime.date(x) + datetime.time(10, 23)
print(x)
You can use datetime.replace():
from datetime import datetime
d = "2015-06-12"
x = datetime.strptime(d, "%Y-%m-%d").replace(hour=10, minute=23)
To print it in desired format you can use datetime.strftime():
print(x.strftime("%Y%m%d %H:%M:%S %Z"))
BUT it won't print timezone name (%Z), cause created datetime object has no information about timezone. You can add it manually, by providing time delta between UTC and timezone:
from datetime import datetime, timezone, timedelta
x = datetime.strptime(d, "%Y-%m-%d").replace(hour=10, minute=23,
tzinfo=timezone(timedelta(hours=6), name="CST"))
Or set local timezone:
x = datetime.strptime(d, "%Y-%m-%d").replace(hour=10, minute=23,
tzinfo=datetime.utcnow().astimezone().tzinfo)
Related
I have this column where the string has date, month, year and also time information. I need to take the date, month and year only.
There is no space in the string.
The string is on this format:
date
Tuesday,August22022-03:30PMWIB
Monday,July252022-09:33PMWIB
Friday,January82022-09:33PMWIB
and I expect to get:
date
2022-08-02
2022-07-25
2022-01-08
How can I get the date, month and year only and change the format into yyyy-mm-dd in python?
thanks in advance
Use strptime from datetime library
var = "Tuesday,August22022-03:30PMWIB"
date = var.split('-')[0]
formatted_date = datetime.strptime(date, "%A,%B%d%Y")
print(formatted_date.date()) #this will get your output
Output:
2022-08-02
You can use the standard datetime library
from datetime import datetime
dates = [
"Tuesday,August22022-03:30PMWIB",
"Monday,July252022-09:33PMWIB",
"Friday,January82022-09:33PMWIB"
]
for text in dates:
text = text.split(",")[1].split("-")[0]
dt = datetime.strptime(text, '%B%d%Y')
print(dt.strftime("%Y-%m-%d"))
An alternative/shorter way would be like this (if you want the other date parts):
for text in dates:
dt = datetime.strptime(text[:-3], '%A,%B%d%Y-%I:%M%p')
print(dt.strftime("%Y-%m-%d"))
The timezone part is tricky and works only for UTC, GMT and local.
You can read more about the format codes here.
strptime() only accepts certain values for %Z:
any value in time.tzname for your machine’s locale
the hard-coded values UTC and GMT
You can convert to datetime object then get string back.
from datetime import datetime
datetime_object = datetime.strptime('Tuesday,August22022-03:30PM', '%A,%B%d%Y-%I:%M%p')
s = datetime_object.strftime("%Y-%m-%d")
print(s)
You can use the datetime library to parse the date and print it in your format. In your examples the day might not be zero padded so I added that and then parsed the date.
import datetime
date = 'Tuesday,August22022-03:30PMWIB'
date = date.split('-')[0]
if not date[-6].isnumeric():
date = date[:-5] + "0" + date[-5:]
newdate = datetime.datetime.strptime(date, '%A,%B%d%Y').strftime('%Y-%m-%d')
print(newdate)
# prints 2022-08-02
I am getting date and time like this
date_time = "2022-02-17 08:29:36.345374"
And to convert these to AM, PM format I am doing something like this
date_formate = datetime.fromisoformat(date_time).strftime('%d/%m/%Y %I:%M %p')
but End time I am getting is in not local time seems it's in UTC , I am trying to convert it in utc but no luck doing something like this
dtUTC = datetime.fromisoformat(date_formate[:-1])
dtZone = dtUTC.astimezone()
print(dtZone.isoformat(timespec='seconds'))
got this solution on stackoverflow but getting error Invalid isoformat string: '2022-02-17 08:29:36.345374'
Python assumes local time by default if you don't specify a time zone / UTC offset. So in this case, you need to set UTC first, then convert, then format (if you want a string as output):
from datetime import datetime, timezone
date_time = "2022-02-17 08:29:36.345374" # UTC is not specified here...
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone()
print(local) # my tz was on UTC+1 at that date...
# 2022-02-17 09:29:36.345374+01:00
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 09:29 AM
If astimezone(None) does not work, you can try tzlocal;
import tzlocal
zone = tzlocal.get_localzone()
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone(zone)
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 09:29 AM
or derive a timezone object from a timedelta, e.g.
from datetime import timedelta
zone = timezone(timedelta(minutes=-300)) # UTC-5 hours
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone(zone)
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 03:29 AM
I have two strings one: date='2021-12-30T23:00Z' where Z means UTC timezone and 23:00 means hour. I also have an hour string hour='3'. What I want is to convert date to datetime object and add this hour string to date as a delta. In result I would get a datetime object with hour: '2021-12-31T02:00Z' I tried function datetime.datetime.fromisoformat() with no luck.
Use strftime with their format.
from datetime import datetime, timedelta
date='2021-12-30T23:00Z'
date = datetime.strptime(date, '%Y-%m-%dT%H:%MZ')
new_date = date + timedelta(hours=3)
new_date = new_date.strftime('%Y-%m-%dT%H:%MZ')
print(new_date)
Output:
2021-12-31T02:00Z
You could do something like this:
from datetime import datetime
from datetime import timedelta
date = "2021-12-30T23:00Z"
hour = "3"
d = datetime.strptime(date, "%Y-%m-%dT%H:%M%z") + timedelta(hours=int(hour))
print(d)
output:
2021-12-31 02:00:00+00:00
I want to change date format using Python. I don't know How to do that.
I have date format as shown below
2020-10-22 12:14:41.293000+00:00
I want to change above date format into below format:
date(2020, 10, 22)
I want this format because I want to get different between two dates.
with above format I can get difference by using following code,
d0 = date(2017, 8, 18)
d1 = date(2017, 10, 26)
delta = d1 - d0
print(delta.days)
So how to Change date Format as I discussed above.and also let me know if anyone know other way to get difference between these two dates 2020-10-22 12:14:41.293000+00:00 and 2020-10-25 12:14:41.293000+00:00 without changing its formet.I will be thankful if anyone can help me with this issue.
use fromisoformat and date() to get only the date, without the time:
from datetime import datetime
d = datetime.fromisoformat('2020-10-22 12:14:41.293000+00:00').date()
# d
# datetime.date(2020, 10, 22)
To convert a string to a datetime object, we use the datetime module.
from datetime import datetime
def str_to_date(s):
s = s.split()[0] # Separate the str by spaces and get the first item (the date)
s = datetime.strptime(s, "%Y-%m-%d")
return s # You now have a datetime object to do operations on.
If the format is always in the form YYYY-MM-DD ..... then you can strip the first 10 characters of the date and use datetime to convert into datetime object
from datetime import datetime
unformatted_date = "2020-10-22 12:14:41.293000+00:00"
date_obj = datetime.strptime(unformatted_date[0:11], "%Y-%m-%d").date()
print(date_obj)
Change string to datetime format:
from datetime import datetime
date1 = datetime.strptime('2020-10-22 12:14:41.293000+00:00', '%Y-%m-%d %H:%M:%S.%f%z').date()
date2 = datetime.strptime('2020-10-23 12:14:41.293000+00:00', '%Y-%m-%d %H:%M:%S.%f%z').date()
print(date2-date1)
#1 day, 0:00:00
I have data with the date format as follows:
date_format = 190410
year = 19
month = 04
date = 10
I want to change the date format, to be like this:
date_format = 10-04-2019
How do I solve this problem?
>>> import datetime
>>> date = 190410
>>> datetime.datetime.strptime(str(date), "%y%m%d").strftime("%d-%m-%Y")
'10-04-2019'
datetime.strptime() takes a data string and a format, and turns that into datetime object, and datetime objects have a method called strftime that turns datetime objects to string with given format. You can look what %y %m %d %Y are from here.
This is what you want(Notice that you have to change your format)
import datetime
date_format = '2019-04-10'
date_time_obj = datetime.datetime.strptime(date_format, '%Y-%m-%d')
print(date_time_obj)
Here is an other example
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)
You can also do this
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
print(date)
There are many ways to achieve what you want.