I'm writing a very simple python program to read in an ascii csv file with multiple records formatted like this:
"2010.3.13, 0.0.0, 10.1, 12.2, 9.9, 10.1, 2500" # i.e. a list of daily stock prices with date,time,open, high,low,close, volume fields
I use this python code to read each line from the ascii file named f:
for line in f: d,t,o,h,l,c,v = line.split(',') # where d stands for date, etc
Much to my pleasant shock, the ascii string "2010.3.13" ends up as a datetime.date object stored in the variable 'd'.
So, how did this pleasant surprise happen? Why isn't that string stored in 'd' as the string "2010.3.13" instead of as a date object?
Python must be sneaking around behind my back doing automagical type conversions, but how/where is it happening?
Thanks!
BTW, I did "import datetime" because I was planning to do all the ugly date conversions myself. That's why I'm pleasantly surprised.
7 3603 Glenton 391
Recognized Expert Contributor
Hi
I got this, so probably you need to post your code to find the "magic"... - In [1]: import datetime
-
-
In [2]: st="2010.3.13, 0.0.0, 10.1, 12.2, 9.9, 10.1, 2500"
-
-
In [3]: d,t,o,h,l,c,v = st.split(',')
-
-
In [4]: d
-
Out[4]: '2010.3.13'
-
-
In [5]: type(d)
-
Out[5]: <type 'str'>
-
Glenton 391
Recognized Expert Contributor
Hi.
I got this, so you probably need to post your code for us to find your magic! - In [1]: import datetime
-
-
In [2]: st="2010.3.13, 0.0.0, 10.1, 12.2, 9.9, 10.1, 2500"
-
-
In [3]: d,t,o,h,l,c,v = st.split(',')
-
-
In [4]: d
-
Out[4]: '2010.3.13'
-
-
In [5]: type(d)
-
Out[5]: <type 'str'>
-
Hrrmph. This morning the magic is gone and I get a string in d, just like you did. Last night I was running the code in a live python session and I obviously did something I can't remember now :(
Today I got the job done with this code instead: -
for lines in f:
-
d,t,o,h,l,c,v = lines.split(',')
-
yr,mo,day = d.split('.')
-
if datetime.date(string.atoi(yr),string.atoi(mo),string.atoi(day)).weekday() < 5: #discard Saturday and Sunday
-
print d,o,h,l,c
The code works, but it looks ugly to me. I'm hoping that python will have a more elegant way to do it. Any suggestions?
Thanks!
Glenton 391
Recognized Expert Contributor
Where did you come across the atoi function?! It's been deprecated since version 2.0. See docs (I had to look it up). Use int(yr),int(mo) ,int(day) instead.
Other than that it seems pretty elegant to me! Terse, efficient, clear. What more would you want? ;D
bvdet 2,851
Recognized Expert Moderator Specialist
Please use code tags when posting code. See Posting Guidelines here.
bvdet 2,851
Recognized Expert Moderator Specialist
You could use time.strptime to convert the string into a struct_time object and time.strftime to convert to another string in a different format. In addition, if the time was of any importance, it could easily be included. Example: - import time
-
data = "2010.3.13, 14.45.7, 10.1, 12.2, 9.9, 10.1, 2500"
-
-
d,t,o,h,l,c,v = [s.strip() for s in data.split(',')]
-
dateObj = time.strptime(d, "%Y.%m.%d")
-
print dateObj
-
-
dateObj1 = time.strptime(".".join([d, t]), "%Y.%m.%d.%H.%M.%S")
-
print dateObj1
-
-
print time.strftime("%c", dateObj1)
Output: - >>> (2010, 3, 13, 0, 0, 0, 5, 72, -1)
-
(2010, 3, 13, 14, 45, 7, 5, 72, -1)
-
03/13/10 14:45:07
For what it's worth, you can convert a struct_time object into a datetime.dateti me object: - >>> import datetime
-
>>> datetime.datetime(*dateObj1[:6])
-
datetime.datetime(2010, 3, 13, 14, 45, 7)
-
>>>
@Glenton
I think perl is less fussy about automatic type conversions, isn't it? Haven't done much with perl, but I got that impression, anyway.
Heh, I got atoi from an O'Reilly Python book I bought in 1999 and just got around to reading last week :)
Thanks to bvdet for the strptime examples, looks useful.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: PK9 |
last post by:
I have a string variable that holds the equivalent of a DateTime value. I
pulled this datetime from the database and I want to strip off the time
portion before displaying to the user.
I am using C#
eg.
- String variable "strMyDate" holds the value "1/1/2005 12:00:00 AM" from
the database.
- I do not care about the time portion, I only want "1/1/2005" for display.
|
by: Hans Merkl |
last post by:
Does anybody know of a library that can handle strings pf various formats
and conver them to a DateTime value? The strings are coming from a webform
and I can't restrict the input (it's not my form).
I have been using Convert.ToDateTime but it choked on "12:00 noon".
I am looking for a function that can make sense out of anything that looks
like a date/time. Outlook is pretty good at it when you enter an
appointment with the GUI, but...
|
by: adolf garlic |
last post by:
I'm having a problem with dates.
(No not the sort that you have at christmas)
I have a webform with a text box and a calendar control.
You can either
- enter a date manually (we are talking uk style here dd/mm/yyyy) in the
textbox
- click a date on the calendar which puts the date value in the textbox (uk
style)
|
by: Glenn M |
last post by:
I have a date stored as a string in the format mm/dd/yyyy.
What is the easiest way to get this date converted to a datetime
object so i can include it in the datediff function.
also what is the method i should use to return a date string back from
the datatime object, possibly in a different format such as dd/mm/yyyy
glenn
|
by: JenHu |
last post by:
Hi expert,
I have a data field (birthdate) contains a datetime datatype
(mm/dd/yyyy), how can I convert to mmdd??
say, the birthday is 8/1/1979 and convert to mmdd
DOB = DS.Tables("AcctInfoTble").Rows(3)("BRTHDATE")
strResult.Insert(12, DOB.PadLeft(37, " "))
---------------------------------------------------------------------------------------------------
| |
by: Lucky |
last post by:
hi guys!
back again with another query.
the problem is like this.
i want to print a line like this:
"---------------------------------------------"
the easiest way is to simply assign it to string and print it.
but i want to use the String.Format() method if possible to do it.
|
by: izziy |
last post by:
Our legacy DB has a bad column which stores a date value as char(8), it has a format like 'MMDDYYYY'.
I am creating a report to report this particular date and also use this date to specify a range.
I tried using this
SELECT Convert(datetime,(substring(c.dateofreceipt,5,4)+'-'+substring(c.dateofreceipt,1,2)+'-'+substring(c.dateofreceipt,3,2)), 102) as dateofreceipt
in query analyzer and it works fine. But in .Net report designer,...
|
by: =?iso-8859-1?B?Qmr2cm4gS2VpbA==?= |
last post by:
Hello pythons,
I have little problem with understanding conversions in python. I've
written a little class - nothing much, just to try out Python a little
- containing the following method:
def __repr__(self):
"""Serializes the note.
Currently the format of notes isn't decided upon. XML output
|
by: Brian Parker |
last post by:
I am beginning to work with VB2005.NET and I'm getting some problems
with string formatting converting an application from VB6.
VB6 code:-
sTradeDate = Format(pArray(4,i Record), "mmddyy")
pArray is a variant array containing a date string at pArray(4,
iRecord) in the format "yyyy/mm/dd"
|
by: rhaazy |
last post by:
I need to know how I can format a string in C# to get the current date/
time, so that I can do a comparison against a date time column in MS
SQL Server 2005.
The date/time column in the database is of the followin format:
mm/dd/yyyy hh:mm:ss AM/PM
thanks in advance.
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |