By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,542 Members | 1,434 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,542 IT Pros & Developers. It's quick & easy.

Picking values from timestamp

P: 3
Dear sirs/madams

I am not sure whether or not this question has already been answered, but I am completely new to perl and my problem is as follows:

I have comma separated values in a text file, which I need to do some stuff with, and the data starts with a timestamp, i.e. on the form "2008-06-13 15:25:00" (the quote marks are part of the data). I need to fish the year, day, hour and minute from this timestamp as seperate integers. Does anyone have a solution how to do this?

Best regards, Sigurjon
Jul 5 '10 #1

✓ answered by toolic

Use a regular expression to extract the date and time into an array:

Expand|Select|Wrap|Line Numbers
  1. use strict; 
  2. use warnings;
  3. use Data::Dumper;
  4.  
  5. my $s = "2008-06-13 15:25:00";
  6. my @tokens = $s =~ /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
  7. print Dumper(\@tokens);
  8.  
  9. __END__
  10.  
  11. $VAR1 = [
  12.           '2008',
  13.           '06',
  14.           '13',
  15.           '15',
  16.           '25',
  17.           '00'
  18.         ];

Share this Question
Share on Google+
4 Replies


Expert
P: 70
Use a regular expression to extract the date and time into an array:

Expand|Select|Wrap|Line Numbers
  1. use strict; 
  2. use warnings;
  3. use Data::Dumper;
  4.  
  5. my $s = "2008-06-13 15:25:00";
  6. my @tokens = $s =~ /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
  7. print Dumper(\@tokens);
  8.  
  9. __END__
  10.  
  11. $VAR1 = [
  12.           '2008',
  13.           '06',
  14.           '13',
  15.           '15',
  16.           '25',
  17.           '00'
  18.         ];
Jul 5 '10 #2

P: 3
Thank you for your post toolic.

Now I have an array of six integers, each representing one part of the timestamp. Can I refer to them individually like this: @tokens[0] (the year) and @tokens[1] (the month)? If not, how would I get them individually?

Best regards, Sigurjon
Jul 5 '10 #3

Expert
P: 70
Expand|Select|Wrap|Line Numbers
  1. $tokens[0]
perlintro
Jul 5 '10 #4

P: 3
Dear toolic.

I tried this solution and it worked perfectly. Problem solved.

Very many thanks to you for your advice!

Best wishes, Sigurjon
Jul 12 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.