Python date conversion? - python

I'm currently trying to convert a file format into a slightly different style to allow easier importing into a program however I can't quite get my head around how to convert datetime strings between formats. The original I have is the following:
2016-12-15 17:26:45
However the required format for the date time is:
Thu Dec 15 17:19:03 2016
Does anyone know if there is an easy way to convert between these? These values are always in the same place and format so it doesn't need to be too dynamic so to speak outside of recognising what a certain day of the month is (if that can be done at all?)
Update - The conversion has worked for 1 date but not the other weirdly :/ The code to grab the two dates is the following:
startDate=startDate.replace("Started : ","")
startDate=startDate.replace(" (ISO format YYYY-MM-DD HH:MM:SS)","")
startDate=startDate.strip()
startDt = datetime.strptime(startDate, '%Y-%m-%d %H:%M:%S')
startDt=startDt.strftime('%a %b %d %H:%M:%S %Y ')
print (startDt)
This part works as inteded and outputs the required format:
"2016-12-15 17:26:45
Thu Dec 15 17:26:45 2016"
The end date part is a bit "ham fisted" so to speak and I'm sure there are better ways to do the re.sub search just to do anything in brackets but I'll edit that later.
endDate=endDate.replace("Ended : ","")
endDate=endDate.strip()
endDate = re.sub("\(.*?\)", "", endDate)
endDate.strip()
endDt = datetime.strptime(endDate, '%Y-%m-%d %H:%M:%S')
endDt=endDt.strftime('%a %b %d %H:%M:%S %Y ')
print (endDt)
This part however despite the outputs being an identical format
"2016-12-15 17:26:45
2016-12-15 21:22:11"
produces the following error:
endDt = datetime.strptime(endDate, '%Y-%m-%d %H:%M:%S')
File "C:\Python27\lib\_strptime.py", line 335, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:

from datetime import datetime
dt = datetime.strptime('2016-06-01 1:33:45', '%Y-%m-%d %H:%M:%S')
dt.strftime('%a %b %d %H:%M:%S %Y ')
>>> 'Wed Jun 01 01:33:45 2016'

It's a pretty easy task with the Datetime module.
As it's been pointed out, checking the docs will get you a lot of useful info, starting from the directives to feed to the strptime and strftime (respectively, parse and format time) functions which you'll need here.
A working example for you case would be:
from datetime import datetime
myDateString = '2016-12-15 17:26:45'
myDateObj = datetime.strptime(myDateString, '%Y-%m-%d %H:%M:%S')
myDateFormat = myDateObj.strftime('%a %b %d %H:%M:%S %Y')
Check out this section of the docs to have a better understanding of the formatting placeholders.

You can use the datetime module:
from datetime import datetime
string = '2016-12-15 17:26:45'
date = datetime.strptime(string, '%Y-%m-%d %H:%M:%S')
date2 = date.strftime("%a %b %d %H:%M:%S %Z %Y")
print(date2)
Output:
Thu Dec 15 17:26:45 2016

Related

How to convert datetime to different timezone?

I'm trying to convert a datetime string into a different timezone. My code works but the result is not what I'm looking for.
I've already tried .localize() and .astimezone but the output is the same.
phtimezone = timezone('Asia/Manila')
test = datetime.datetime.strptime('Sun Sep 16 03:38:40 +0000 2018','%a %b %d %H:%M:%S +0000 %Y')
date = phtimezone.localize(test)
print (date)
date = test.astimezone(phtimezone)
print (date)
The output is 2018-09-16 03:38:40+08:00. I was expecting it to be 2018-09-16 11:38:40+08:00.
Your parsed object test does not contain a timezone. It's a naïve datetime object. Using both localize and astimezone cannot do any conversion, since they don't know what they're converting from; so they just attach the timezone as given to the naïve datetime.
Also parse the timezone:
datetime.strptime('Sun Sep 16 03:38:40 +0000 2018','%a %b %d %H:%M:%S %z %Y')
^^
This gives you an aware datetime object in the UTC timezone which can be converted to other timezones.
I was able to fix it thanks to #deceze. Here is the code:
phtimezone = pytz.timezone('Asia/Manila')
test = datetime.datetime.strptime('Sun Sep 16 03:38:40 +0000 2018','%a %b %d %H:%M:%S %z %Y')
test_utc = test.replace(tzinfo=timezone('UTC'))
date = test_utc.astimezone(pytz.timezone('Asia/Manila'))
print (date)
The output is now 2018-09-16 11:38:40+08:00

Python: Date Conversion Error

I'm trying to convert a string into a date format, to be later stored into an SQLite database. Below is the code line at which I'm getting an error.
date_object = datetime.strptime(date, '%b %d, %Y %H:%M %Z')
And this is the error:
File "00Basic.py", line 20, in spider
date_object = datetime.strptime(date, '%b %d, %Y %H:%M %Z') File "C:\Python27\lib\_strptime.py", line 332, in _strptime
(data_string, format)) ValueError: time data 'Aug 19, 2016 08:13 IST' does not match format '%b %d, %Y %H %M %Z'
Question 1: How do I resolve this error?
Question 2: Is this the right approach for preparing to store the date in SQLite later?
Please Note: Very new to programming.
You could use pytz for the timezone conversion as shown:
from datetime import datetime
from pytz import timezone
s = "Aug 19, 2016 08:13 IST".replace('IST', '')
print(timezone('Asia/Calcutta').localize(datetime.strptime(s.rstrip(), '%b %d, %Y %H:%M')))
#2016-08-19 08:13:00+05:30
#<class 'datetime.datetime'>
I would suggest you to use dateutil incase you are handling multiple timezones of string.
The problem is located in the %Z (Time zone) part of the format.
As the documentation explains
%Z Time zone name (empty string if the object is naive). (empty), UTC, EST, CST
It looks like only UTC,EST and CST are valid. (Or it just doesn't recognize IST)
In order to fix this, you could use the %z parameter that accepts any UTC offset, like so:
struct_time = time.strptime("Aug 19, 2016 08:13 +0530", '%b %d, %Y %H:%M %z')
Update: Although this works fine in Python +3.2 it raises an exception when it's run with Python2

Converting String to Date Format in Python

I have the following date I need to convert:
Wed, 09 Jul 2014 12:22:17 +0000
This is currently stored as a String. I wrote this code to convert it to the date format I want (the String above is passed as an argument to the covertDate function):
def convertDate(dictValue):
date_string = dictValue
format_string = '%a, %d %b %Y %H:%M:%S %z'
date_object = datetime.datetime.strptime(date_string, format_string)
date_correct_form = date_object.strftime("%Y-%m-%d")
print(type(date_correct_form))
print(date_correct_form)
return date_correct_form
The output is as follows:
<class 'str'>
2014-10-30
I get the format that I want, but it still isn't recognized as a date.
How can I make it so?
You are returning date_correct_form, which is the result of strftime:
Return a string representing the date, controlled by an explicit format string.
(emphasis mine)
If you want the datetime object, return date_object. If you need both, you can return both:
return date_correct_form, date_object
You can call it like so:
date_string, date_obj = convertDate(dictValue)
You now have the already formatted string in date_string, and if you still need to do logic against the datetime object, that is in date_obj
You can use easy_date to make it easy:
import date_converter
converted_date = date_converter.string_to_date(date_string, '%a, %d %b %Y %H:%M:%S %z')

String to Time Python strptime

I'm pulling the date value from gmail and trying to perform some functions on it. First I simply want to display it, but I can't even do that. See my code and error below.
from datetime import datetime
timeString = 'Sat, 2 Aug 2014 09:29:31 -0700'
myTime = datetime.strptime(timeString, '%m-%d-%Y %I:%M %p')
Here's the error I get. Do you think its the -0700 that's getting in the way?
ValueError: time data 'Sat, 2 Aug 2014 09:29:31 -0700' does not match format '%m-%d-%Y %I:%M %p'
As the error message suggests, you need to put the same format as your date string is in, I've not tried it, but something like this should work:
myTime = datetime.strptime(timeString, '%a, %d %b %Y %I:%M:%S %z')
Check here for complete details.

date format with timezone

How do I format a date in python to look like this: weekday:month:day(number):HH:MM:SS(military):EST/CST/PST:YYYY? I am familiar with strftime(), but I am unsure how I would handle the HH:MM:SS and EST/CST/PST.
example of how I am trying to get the date to look:
Sun Mar 10 15:53:00 EST 2013
from time import gmtime, strftime
print strftime("%a %b %d %H:%M:%S %Z %Y", gmtime())
This will produce
Fri Mar 22 21:10:56 Eastern Standard Time 2013
You'll have to settle for the long name of the timezone unless you want to use pytz. I suppose it's worth noting that timezone abbreviations aren't unique.
Use strftime to output a formatted string representation:
print time.strftime("%a %b %d %H:%M:%S %Z %Y")
A list of the format codes can be found here

Categories